有三个Activity: A.java ,B.java ,C.java
Activity之间的跳转常用方法:
1. startActivity(Intent intent);
该方法只用于启动新的Activity
2.startActivityForResult(Intent intent, int requestCode);
该方法做两件事:一.启动新的Activity 二.回收启动的Activity返回的结果
(1)A.java中
startActivityForResult(Intent intent, int requestCode);
requestCode: 是自定义的int型常量, requestCode >=0。
例:
1
2
3
4
5
6
7
|
if (条件){ Intent intent = new Intent( this , B. class ); startActivityForResult(intent, REQUEST_CODE_01); //跳转至B.java } else { Intent intent = new Intent( this , C. class ); startActivityForResult(intent, REQUEST_CODE_02); //跳转至C.java } |
(2)B.java 或者C.java
setResut(int resultCode, Intent intent)
resultCode:用于标识B.java几种不同的返回结果。没有特殊情况时,用RESULT_OK。
例:
1
2
3
|
Intent intent = new Intent(); intent.putExtra(key, value); // 或者将数据打包到Bundle setResult(RESULT_OK, intent); |
(3)A.java
onActivityResult(int requestCode, int resultCode, Intent data)
requestCode: 用于区分哪个子模块回传的数据。
data: 回传的数据。
Bundle b = data.getExtras();
String str = b.getString("string");
resultCode: 与setResult()中相对应
例:
1
2
3
4
5
6
7
8
9
10
11
|
public void onActivityResult( int requestCode, int resultCode, Intent data){ switch (requestCode) { case REQUEST_CODE_01: if (resultCode==Activity.RESULT_OK) //do something break ; case REQUEST_CODE_02: //do something break ; } } |