逻辑写到子fragment中,父fragment里还需要写逻辑吗
时间: 2024-03-07 15:50:18 浏览: 23
如果你将逻辑写在子 Fragment 中,那么父 Fragment 中就不需要再写相应的逻辑了,因为子 Fragment 在父 Fragment 中的作用就相当于一个普通的视图控件,只是它的内容是通过代码动态生成的而已。
当然,如果你需要在父 Fragment 中与子 Fragment 进行交互(如获取子 Fragment 中的数据、改变子 Fragment 中的 UI 等),那么可以通过 `getChildFragmentManager().findFragmentById()` 或 `getChildFragmentManager().findFragmentByTag()` 方法来获取子 Fragment 的实例,然后调用子 Fragment 中相应的方法进行交互。
以下是一个在父 Fragment 中获取子 Fragment 并进行交互的示例代码:
```
public class ParentFragment extends Fragment {
private ChildFragment mChildFragment;
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// 获取子 Fragment
mChildFragment = (ChildFragment) getChildFragmentManager().findFragmentById(R.id.child_fragment);
// 与子 Fragment 进行交互
if (mChildFragment != null) {
// 获取子 Fragment 中的数据
String data = mChildFragment.getData();
// 改变子 Fragment 中的 UI
mChildFragment.updateUI();
}
}
// ...
}
```
需要注意的是,如果你需要在父 Fragment 中与子 Fragment 进行交互,那么在子 Fragment 中也需要提供相应的方法供父 Fragment 调用。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![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)