IntentActivityTest
public class IntentActivityTest extends Activity {
protected static final int REQUEST_CODE = 1;
private Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(IntentActivityTest.this,SecondActivity.class);
intent.putExtra("activityMain", "数据来自activityMain");
//startActivity(intent);
//如果在activity上要求返回值,那么启动的方法是
startActivityForResult(intent, REQUEST_CODE);
}
});
}
//由子activity返回到父activity时,调用此方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//判断是不是需要的请求码
if (requestCode == REQUEST_CODE){
//判断由Activity返回的结果码
if(resultCode == RESULT_CANCELED) {
setTitle("取消");
}
else if(resultCode == RESULT_OK){
String tmp = null;
Bundle extras = data.getExtras();
if(extras != null) {
tmp = extras.getString("store");
}
setTitle(tmp);
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(tmp);
}
}
}
}
----------------------------------------------------------------------------------------------
子activity demo
public class SecondActivity extends Activity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.onCreate(savedInstanceState);
setContentView(R.layout.two);
button = (Button) findViewById(R.id.button2);
setTitle("Activity2");
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
if(extras != null) {
String data = extras.getString("activityMain");
setTitle(data);
}
Bundle bundle = new Bundle();
bundle.putString("store","数据来自SecondActivity");
Intent mIntent = new Intent();
mIntent.putExtras(bundle);
//设置传递给父activity的Bundle
setResult(RESULT_OK,mIntent);
finish();
}
});
}
}
摘自 ch_jinyi的专栏
补充:移动开发 , Android ,