Fragment如何拿到返回的参数
时间: 2024-02-17 13:05:18 浏览: 11
在 Fragment 中拿到返回的参数可以通过以下步骤实现:
1. 在 Activity 中启动 Fragment,通过 Bundle 将需要传递的数据传递给 Fragment。
```
Bundle bundle = new Bundle();
bundle.putString("data", yourData);
YourFragment fragment = new YourFragment();
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment)
.commit();
```
2. 在 Fragment 中通过 getArguments() 方法获取传递的数据。
```
Bundle bundle = getArguments();
String yourData = bundle.getString("data");
```
3. 在 Fragment 中启动新的 Activity 并等待返回结果,可以通过 startActivityForResult() 方法启动 Activity。
```
Intent intent = new Intent(getActivity(), YourActivity.class);
startActivityForResult(intent, REQUEST_CODE);
```
4. 在 Fragment 中重写 onActivityResult() 方法,获取返回的数据。
```
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == Activity.RESULT_OK) {
String yourData = data.getStringExtra("data");
// 处理返回的数据
}
}
```
需要注意的是,在 Fragment 中启动 Activity 并获取返回的数据时,需要在 Fragment 中重写 onActivityResult() 方法,而不是在 Activity 中重写。同时,启动 Activity 时需要使用 getActivity() 方法获取 Activity 的上下文。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)