Fragment的生命周期和状态
onCreateView()
和onViewCreated()
的区别
-
onCreateView()
返回的就是fragment要显示的view; -
onViewCreated()
在onCreateView()
执行完后立即执行。
一个完整的Android Activity和fragment的生命周期对比
方法 | 描述 |
---|---|
onAttach() | 托管Fragment到Activity中,绑定Fragment |
onCreate() | 创建Fragment时调用,初始化一段资源文件 |
onCreateView() | 在Fragment首次绘制其用户界面时调用。从该方法中返回的 View 必须是Fragment布局的根视图。如果Fragment未提供 UI,返回 null。 |
onViewCreated() | 在Fragment被绘制后,调用此方法,可以初始化控件资源。 |
onActivityCreated() | |
onStart() | |
onResume() | |
onPause() | 此方法作为用户离开Fragment的第一个信号(但并不意味着此Fragment会被销毁) |
onStop() | |
onDestroyView() | Fragment中的布局被移除时调用。 |
onDestory() | |
onDetach() | 解绑Fragment |
Fragment使用
静态用法
- 继承Fragment,重写
onCreateView()
决定Fragment的布局 - 在Activity中声明此Fragment,就当和普通的View一样
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_use_confirm, container, false);
}
动态用法
public class MainActivityextendsActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Display display = getWindowManager().getDefaultDisplay();
if (display.getWidth() > display.getHeight()) {
Fragment1 fragment1 = new Fragment1();
getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment1).commit();
} else {
Fragment2 fragment2 = new Fragment2();
getFragmentManager().beginTransaction().replace(R.id.main_layout, fragment2).commit();
}
}
首先,获取屏幕的宽度和高度,然后进行判断,如果屏幕宽度大于高度就添加fragment1,如果高度大于宽度就添加fragment2。动态添加Fragment主要分为4步:
- 获取到
FragmentManager
,在Activity中可以直接通过getFragmentManager
得到; - 开启一个事务,通过调用
beginTransaction
方法开启; - 向容器内加入Fragment,一般使用replace方法实现,需要传入容器的id和Fragment的实例;
- 提交事务,调用
commit
方法提交。