android 动态加载fragment
时间: 2023-07-21 11:05:02 浏览: 61
动态加载Fragment可以通过FragmentTransaction来完成。具体步骤如下:
1.获取FragmentManager对象
在Activity中获取FragmentManager对象的方式如下:
```
FragmentManager fragmentManager = getFragmentManager();
```
在Fragment中获取FragmentManager对象的方式如下:
```
FragmentManager fragmentManager = getActivity().getFragmentManager();
```
2.开启事务
```
FragmentTransaction transaction = fragmentManager.beginTransaction();
```
3.添加Fragment
```
YourFragment fragment = new YourFragment();
transaction.add(R.id.container, fragment);
```
其中,R.id.container表示Fragment要添加到哪个布局中。
4.提交事务
```
transaction.commit();
```
完整代码示例:
```
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
YourFragment fragment = new YourFragment();
transaction.add(R.id.container, fragment);
transaction.commit();
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)