Android: Fragment 的使用指南
Android 中 Fragment 的使用指南
Fragment 是 Android 应用开发中的重要组件,它代表 Activity 中的一部分 UI 或行为,可以组合多个 Fragment 在一个 Activity 中构建多窗格 UI,并在不同 Activity 中重复使用某个 Fragment。
基本概念
Fragment 具有自己的生命周期,但依赖于宿主 Activity 的生命周期。每个 Fragment 都有自己的布局和行为。
创建 Fragment
1. 定义 Fragment 类
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// 膨胀 fragment 的布局
return inflater.inflate(R.layout.fragment_my, container, false);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// 在这里初始化视图和逻辑
}
}
2. 创建 Fragment 的布局文件 (res/layout/fragment_my.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Fragment!" />
</LinearLayout>
添加 Fragment 到 Activity
方式1: 在 XML 布局中添加 (静态方式,不推荐)
<!-- activity_main.xml -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="@+id/myFragment"
android:name="com.example.MyFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
方式2: 在代码中动态添加 (推荐)
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 检查是否已经添加了Fragment(防止旋转时重复添加)
if (savedInstanceState == null) {
// 创建Fragment实例
MyFragment fragment = new MyFragment();
// 开始Fragment事务
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, fragment) // 添加到容器
.commit();
}
}
}
对应的 activity_main.xml 需要有一个容器:
<FrameLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Fragment 事务
可以执行添加、移除、替换等操作:
// 替换Fragment
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, new AnotherFragment())
.addToBackStack(null) // 允许用户按返回键返回上一个Fragment
.commit();
Fragment 生命周期
Fragment 的生命周期方法:
onAttach()
- Fragment 与 Activity 关联时调用onCreate()
- Fragment 创建时调用onCreateView()
- 创建 Fragment 的视图层次结构onActivityCreated()
- Activity 的 onCreate() 完成后调用onStart()
- Fragment 可见时调用onResume()
- Fragment 可交互时调用onPause()
- Fragment 不再可交互时调用onStop()
- Fragment 不可见时调用onDestroyView()
- Fragment 的视图被移除时调用onDestroy()
- Fragment 不再使用时调用onDetach()
- Fragment 与 Activity 解除关联时调用
Fragment 与 Activity 通信
1. Fragment 调用 Activity 方法
// 在Fragment中
if (getActivity() instanceof MyActivityInterface) {
((MyActivityInterface) getActivity()).doSomething();
}
// Activity实现接口
public interface MyActivityInterface {
void doSomething();
}
2. Activity 调用 Fragment 方法
MyFragment fragment = (MyFragment) getSupportFragmentManager()
.findFragmentById(R.id.my_fragment);
if (fragment != null) {
fragment.doSomethingInFragment();
}
3. 使用 ViewModel 共享数据 (推荐)
// 创建共享ViewModel
public class SharedViewModel extends ViewModel {
private final MutableLiveData<String> selected = new MutableLiveData<>();
public void select(String item) {
selected.setValue(item);
}
public LiveData<String> getSelected() {
return selected;
}
}
// 在Activity或Fragment中获取
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(this, item -> {
// 更新UI
});
最佳实践
- 使用
androidx.fragment.app
包中的 Fragment(支持库版本) - 避免在 Fragment 中直接持有 Activity 的引用
- 使用接口进行 Fragment 与 Activity 的通信
- 考虑使用 ViewModel 和 LiveData 进行数据共享
- 合理使用
addToBackStack()
管理返回栈 - 为 Fragment 添加标签,便于查找:
.add(R.id.container, fragment, "TAG")
高级用法
1. Fragment 参数传递
// 创建Fragment时传递参数
public static MyFragment newInstance(String param) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putString("key", param);
fragment.setArguments(args);
return fragment;
}
// 在Fragment中获取参数
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
String param = getArguments().getString("key");
}
}
2. 使用 Navigation 组件管理 Fragment
// 在build.gradle中添加依赖
implementation "androidx.navigation:navigation-fragment:2.3.5"
// 使用NavController导航
NavController navController = Navigation.findNavController(view);
navController.navigate(R.id.action_to_next_fragment);