在Activity中有个onActivityResult方法,如果Activity A使用startActivityForResult方法跳转到其他Activity,当再次返回到Activity A时就会触发onActivityResult方法。
先写下使用总结:
1.创建一个REQUST_CODE
2.在Activity A通过startActivityForResult启动Activity B
3.在Activity B中使用intent携带数据,setResult设置数据结果,在finish方法执行后返回结果数据
4.在Activity A中使用onActivityResult方法,根据不同的request_code,从Intent中获取数据做不同处理。
来说下onActivityResult中的参数:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data)
resultCode:结果码,通常情况下都会返回RESULT_OK(-1),其他两种没有试出来。
data:intent用于传递返回的数据。
自己写了个demo来测试onActivityResult方法:
MainActivity:
public class MainActivity extends AppCompatActivity { private Button btnEnter01,btnEnter02; private TextView tvResult,tvResult02; private final static int REQUEST_CODE = 1000;//设置请求码 private final static int REQUEST_CODE_02 = 1001;//设置请求码 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnEnter01 = (Button) findViewById(R.id.btnEnter); btnEnter02 = (Button) findViewById(R.id.btnEnter02); tvResult = (TextView) findViewById(R.id.tvResult); tvResult02 = (TextView) findViewById(R.id.tvResult02); btnEnter01.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(MainActivity.this,FirstActivity.class),REQUEST_CODE);//发送请求码并进入第二个Activity } }); btnEnter02.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivityForResult(new Intent(MainActivity.this,SecondActivity.class),REQUEST_CODE_02); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); Log.e("uding", "in onActivityResult"); Log.e("uding","requestCode = " + requestCode + " resultCode = " + resultCode); /*这里实测了RESULT_FIRST_USER和RESULT_CANCELED,结果发现返回的都是RESULT_OK*/ if (resultCode == RESULT_OK){//当第二个Activity中结果码为RESULT_OK if (requestCode == REQUEST_CODE) {//这里通过startActivityForResult方法中的REQUEST_CODE来判断(如果有多个) String result = data.getExtras().getString("RESULT_STRING"); tvResult.setText(result); } if (requestCode == REQUEST_CODE_02){ String result = data.getExtras().getString("RESULT_STRING"); tvResult02.setText(result); } } } }
FirstActivity:
public class FirstActivity extends AppCompatActivity { private Button btnBack; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_first); btnBack = (Button) findViewById(R.id.btnBack); btnBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(); i.putExtra("RESULT_STRING","FirstActivity接收成功"); setResult(Activity.RESULT_OK, i); finish(); } }); } }
SecondActivity和FirstActivity的代码一样的,就不贴出来了。
运行结果:从MainActivity分别跳转到FirstActivity和SecondActivity,在返回到MainActivity后,两个TextView的内容都改变了。