Android中的Fragment其实和我们web前端开发的Iframe有点像,就是在一个大的布局文件中嵌入各种小的布局。当然说的不正确,但是对于初学者来说,这么理解确实最好的。
一、静态操作
静态操作最简单,直接在布局文件中写入Fragment组件就可以了。
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:name="com.example.MyFragment"
android:id="@+id/my_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
- name:就是自己新建的Fragment类的地址。
二、动态操作
- 第一步,创建Fragment类。MyFragment这是自己创建的Fragment类。
MyFragment fragment = new MyFragment();
- 第二步,获取Fragment的管理器。
FragmentManager fragmentManager = getSupportFragmentManager();
动态创建Fragment
// 创建Fragment实例
MyFragment fragment = new MyFragment();
// 获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// 开启事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 添加Fragment到容器中
transaction.add(R.id.container, fragment, "tag");
// 提交事务
transaction.commit();
动态删除Fragment
// 获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// 查找要删除的Fragment
MyFragment fragment = (MyFragment) fragmentManager.findFragmentByTag("tag");
if (fragment != null) {
// 开启事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 删除Fragment
transaction.remove(fragment);
// 提交事务
transaction.commit();
}
动态更换Fragment
// 创建新的Fragment实例
NewFragment newFragment = new NewFragment();
// 获取FragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
// 开启事务
FragmentTransaction transaction = fragmentManager.beginTransaction();
// 替换当前Fragment为新的Fragment
transaction.replace(R.id.container, newFragment, "new_tag");
// 提交事务
transaction.commit();