Activity 換頁後回傳資訊
AndroidManifest.xml 註冊 Activity
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.chriske" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".OtherActivity"
android:label="@string/app_name"/>
</application>
</manifest>
建立第二個 Activity
public class OtherActivity extends Activity {
private Activity activity;
private int returnValue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
returnValue = (int) (Math.random() * 100);
Button backPage = new Button(this);
backPage.setText("回傳 " + returnValue);
setContentView(backPage);
backPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bundle argument = new Bundle();
argument.putInt("returnValueName", returnValue);
Intent intent = getIntent();
intent.putExtras(argument);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
}
}
從第一個 Activity 移動到第二個 Activity
public class MainActivity extends Activity {
private Activity activity;
private Button toNextPage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = this;
toNextPage = new Button(this);
setContentView(toNextPage);
toNextPage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent goOtherActivity = new Intent(activity, OtherActivity.class);
activity.startActivityForResult(goOtherActivity, 0);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
Bundle argument = data.getExtras();
String value = String.valueOf(argument.getInt("returnValueName"));
toNextPage.setText("取得:" + value);
}
}
}