Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivityForResult(intent,1);
//使用startActivityForResult方法开启SecondActivity,第一个参数是Intent对象,第二个参数数请求码,用于标识请求的来源
Intent intent=new Intent();
intent.putExtra("data","Hello MainActivity");
setResult(2,intent);//第一个为返回码,标识是哪个返回数据
finish();
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(requestCode==1&&resultCode==2){
String result=data.getStringExtra("data");//获取回传的数据
Toast.makeText(MainActivity.this,acquiredData,Toast.LENGTH_LONG).show();
}
}
实战演示:
activity_main中点击数据回传按钮
跳转到activity_third中,在activity_third中点击数据回传,在activity_main中输出
MainActivity中设置数据回传按钮事件:
Intent intent2=new Intent(MainActivity.t
startActivityForResult(intent2,1);
然后再ThirdActivity中对回传数据按钮设置点击事件:
Intent intent=new Intent();
intent.putExtra("data","Hello MainActivity");
setResult(2,intent);
finish();
最后再MainActivity中获取回传数据并显示:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==1&&resultCode==2){
String result=data.getStringExtra("data");
Toast.makeText(MainActivity.this,result,Toast.LENGTH_LONG).show();
}
}