Activity之间的跳转
# 直接跳转
# 显示跳转
# 隐式跳转
# 启动带返回值的Activity
为什么需要请求码:
作为返回身份的标识。因为同一个界面可能请求多个带返回值的不同的Activity,需要辨别具体是哪个Activity返回的数据,从而区分到底是请求的谁来返回数据(MainActivity同时请求Activity1、Activity2、Activity3)
# 启动源
在启动源中,调用
startActivityForResult()
激活新的Activitypublic void startActivityForResult(Intent intent, int requestCode)
1当被启动的Activity返回结果时,启动源的
onActivityResult()
会被调用prtected void onActivityResult(int requestCode, int resultCode, Intent data)
1
# 被启动Activity添加返回的数据
在被启动的Activity中,将数据添加(封装)到Intent对象中,调用
setResult()
public void setResult(int resultCode, Intent data)
1被启动的Activity结束时,启动源中
onActivityResult()
会被 回调,结束Acitvity调用finish()
public void finish()
1【案例实现】
MainActivity
/**
* @Author: iqqcode
* @Date: 2021/3/7
* @Description:带回调启动与带结果返回
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mtv_context = null;
private Button mbtn_next = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mtv_context = findViewById(R.id.tv_context);
mbtn_next = findViewById(R.id.btn_next);
mbtn_next.setOnClickListener(this);
}
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(intent, 101);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mtv_context.setText("第二个Activity返回结果显示: \n\n\n" + data.getStringExtra("data"));
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
SecondActivity
public class SecondActivity extends AppCompatActivity {
private EditText meditText = null;
private Button mButton = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
meditText = findViewById(R.id.ed_edit);
findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("data", meditText.getText().toString());
setResult(200, intent);
finish();
}
});
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# APP1跳转到APP2
编辑 (opens new window)
上次更新: 2022/03/27, 22:58:50