1、 startActivityForResult()和startActivity()
startActivity()仅仅只是页面的跳转,如果想跳转回到原页面,还需要再使用一次startActivity().
startActivityForResult()可以直接完成上述任务,例如从A1 Activity跳转到A2 Activity,当A2 Activity调用了finish()方法以后,程序就会自动跳回A1 Activity并调用A1 Activity中的onActivityResult( )方法
2、主要函数
startActivityForResult(Intent intent, Int requestCode) A1
setResut(int resultCode, Intent intent) A2
onActivityResult(int requestCode, int resultCode, Intent intent) A1
A1 Activity中的startActivityForResult
toSecondButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(FirstActivity.this, SecondActivity.class);
intent.putExtra("str", "I'm back");
startActivityForResult(intent, BACK1); //此处BACK1为1,也可以为其他值,但一定大于等于0
}
});
A1 Activity中重写onActivityResult方法(从A2返回后执行)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case BACK1:
Bundle bundle=data.getExtras();
String string=bundle.getString("back1");
Toast.makeText(FirstActivity.this,string,Toast.LENGTH_SHORT).show();
break;
case BACK2 :
Bundle bundle2=data.getExtras();
String string2=bundle2.getString("back2");
Toast.makeText(FirstActivity.this,string2,Toast.LENGTH_SHORT).show();
break;
case BACK3:
Bundle bundle3=data.getExtras();
String string3=bundle3.getString("ID");
textView.setText(string3);
Toast.makeText(FirstActivity.this,string3,Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
A2 Activity中的setResut
back1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("back1","back button1"); //back button1"为传递的内容
setResult(BACK1, intent); //BACK1为resultcode
intent.setClass(SecondActivity.this,FirstActivity.class);
finish(); //一定要有
}
});