Activity1跳转到Activity2,用startActivity();如果由Activity1跳转到Activity2,需要再由Activity2回到Activity1呢?
可能有人说:那我在Activity2中再次使用startActivity()不就可以了,是的,但是startActivityForResult()能够直接完成这项工作
Activity startActivityForResult(Intent intent,int requestCode)步骤:---requestCode--0--用此来做个标记,要求大于等于0
1)在源Activity中使用startActivityForResult()方法启动目标Activity
2)在目标Activity中使用setResult()方法设置返回值,并调用finish()方法结束目标Activity
3)在源Activity中重写onActivityResult()方法,获得从目标Activity中返回的值
源Activity代码:
public class MainActivity extends Activity {
private Button button;
private void setupView() {
button = (Button) findViewById(R.id.button);
button.setText("启动TargetActivity");
}
public void doClick(View v){
//启动目标Activity
Intent intent = new Intent(this,TargetActivity.class);
intent.putExtra("name", "zhangsan");
// startActivity(intent);
startActivityForResult(intent, 0);
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupView();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
// super.onActivityResult(requestCode, resultCode, data);
switch (resultCode) {
case RESULT_CANCELED:
Toast.makeText(this, "未正确返回结果.", Toast.LENGTH_LONG).show();
break;
case RESULT_OK:
int age = data.getIntExtra("age", -1);
if(age!=-1){
Toast.makeText(this, "返回的年龄是:" + age, Toast.LENGTH_LONG).show();
}
break;
}
}
}
目标Activity代码:
public class TargetActivity extends Activity {
private Button button;
private String name;
private void setupView(){
button = (Button)findViewById(R.id.button);
button.setText("返回");
}
public void doClick(View v){
//判断姓名,根据姓名获取对应的年龄
int age = -1;
if("zhangsan".equals(name)){
age = 19;
}else if("lisi".equals(name)){
age = 20;
}else if("wangwu".equals(name)){
age = 30;
}else{
age = 18;
}
//创建intent对象,设置年龄为附加参数
Intent intent = new Intent();
intent.putExtra("age", age);
//设置返回值,将intent对象作为数据返回到源Activity
setResult(RESULT_OK, intent);
finish();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupView();//初始化界面
//获取源Activity传递过来的姓名信息
name = getIntent().getStringExtra("name");
//如果未正确获得姓名,则返回RESULT_CALCELED
if(name==null){
setResult(RESULT_CANCELED);
finish();
}
}
}