主要为了方便,节省代码。需要重写onActivityResul(int requestCode, int resultCode, Intent data)方法。requestCode是使用startActivityForResult(intent intent,int requestCode)的code,值需要大于等于零。ResultCode是从另一个activity返回的值,需要在另一个Activity中设置setResult(int RESULT_OK,intent),让后根据resultCode判断是从哪一个Activity返回的值,在进行相应的处理。
//MainActiviyt.java
EditText et1 ;
Button btn1 ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main) ;
btn1 = (Button) findViewById(R.id.main_btn1) ;
et1 = (EditText) findViewById(R.id.main_et1) ;
btn1.setText("传送Bundle值") ;
btn1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent() ;
intent.setClass(MainActivity.this, AnotherActivity.class) ;
Bundle bundle = new Bundle() ;
bundle.putString("name",et1.getText().toString()+ "*") ;
intent.putExtras(bundle) ;
startActivityForResult(intent,0) ;
// startActivity(intent) ;
// MainActivity.this.finish() ;
}
}) ;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO 自动生成的方法存根
switch(resultCode){
case RESULT_OK :
Toast.makeText(MainActivity.this, "D", Toast.LENGTH_LONG).show() ;
Bundle bundle = data.getExtras() ;
et1.setText(bundle.getString("age")) ;
// et1.setText(data.getExtras().getString("age")) ;
break ;
default: ;
}
}
//AnotherActivity.java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_another) ;
Bundle bundle = this.getIntent().getExtras() ;
String name = bundle.getString("name") ;
setTitle(name) ;
Button btn = (Button) findViewById(R.id.activity_another_btn) ;
btn.setText("返回") ;
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle bundle = new Bundle() ;
bundle.putString("age", "23") ;
AnotherActivity.this.getIntent().putExtras(bundle) ;
AnotherActivity.this.setResult(RESULT_OK,AnotherActivity.this.getIntent()) ;
// Intent intent = new Intent() ;
// intent.setClass(AnotherActivity.this, MainActivity.class) ;
// intent.putExtra("age", "0024") ;
// AnotherActivity.this.setResult(RESULT_OK, intent) ;
// System.out.println(AnotherActivity.this.getIntent().getClass());
AnotherActivity.this.finish() ;
}
});
}