android 动态加载fragment
时间: 2023-07-21 18:05:02 浏览: 115
Android 动态添加Fragment的实例代码
动态加载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();
```
阅读全文