fragment(1)

157 阅读2分钟

「这是我参与11月更文挑战的第16天,活动详情查看:2021最后一次更文挑战

1、Fragment的生命周期分析****

Fragment的生命周期主要有:

onAttach()->onCreate()->onCreateView()->onActivityCreated()->onStart()->onResume()->onPause->onStop()->onDestoryView()->onDestory()->onDetach()。

(1) onAttach()

    将Fragment和Activity相关联。在使用时我们通常会使用以下代码添加fragment

getSupportFragmentManager().beginTransaction() .add(R.id. frame_container , msg_fragment );

此时将fragment添加到Activity中,则会首先调用onAttach()方法。

(1) onCreate()

         创建Fragment对象

  (2) onCreateView()

          在创建Fragment视图时调用

 public View onCreateView(LayoutInflater inflater, ViewGroup container,  

                          Bundle savedInstanceState) {  

     return inflater.inflate(R.layout.fragment3, container, false);  

 }
 

通过LayoutInflater的inflate()方法,来绑定xml文件,从而完成视图创建

这里的inflate()方法,

第一个参数为布局文件,

第二个参数为ViewGroup root,表示父窗口,如果返回null,表示没有父窗口,则该Fragment无法显示;

第三个参数,attchToRoot,如果为true,则表示,当前Fragment的xml的根节点作为整个Activity的根节点,此时Acrtivity的其他控件都将不显示。

(4)onActivityCreated()

在Activity的onCreate()方法结束后调用。此时Activity已经完成创建。但此时Activity并不一定是在onCreate()生命周期,可能在onResume()周期中,因为Fragment的添加在Activity的onResume()时进行,也可能是在Activity的onCreate()时进行。

(5)onStart()

与Activity的onStart()相绑定,此时Fragment对于用户已经可见,但是无法交互。

(6)onResume()

            与Activity的onResume()相绑定,在onResume()方法之后就可以与用户交互了。

  (7)onPause()

            与 Activity的onPause()想绑定,且意义与Activity相同

  (8)onStop()

           与Activity的onStop()相绑定,意义也与Activity相同。

(9)onDestoryView()

FragmentManager****

        在Fragment即将结束结束或者保存,此时会回调此方法,用于将onCreateView的视图和fragment分离,而要重新显示的话,需要重新创建视图,介于Activity的onStop和onDestory之间调用。

    FragmentManger是Fragment的管理器,主要用来对Activity中的Fragment进行管理,比如获取Fragmen事务、执行回退栈的出栈等。

  它是一个抽象类,因此通常我们使用它的子类FragmentManagerImpl。

  FragmentManagerImpl的常用方法,如下表 1:

image.png

image.png

FragmentTransaction

FragmentTransaction是Fragment事务类, 主要用于对Activity中Fragment进行操作,比如add,remove,replace,hide,,show等。

        它是一个抽象类,通常我们使用它的子类 BackStackRecord。

        常用的方法如下表 2:

image.png

image.png

例:

image.png

MainActivity:

image.png 使用transaction的 replace()方法实现点击按钮切换fragment

生命周期观察:

image.png

当程序开始运行时,GreenFragment启动,在MainActivity执行onCreate后,当

GreenFragment执行 onStart后,MainActivity继续执行到onResume,

之后GreenFragment才执行onResume

image.png 当退出时,情况如图.

image.png

当从GreenFragment跳到RedFragment时,看到RedFragment先执行周期,等到绑定完,创建RedFragment对象后,GreenFragment才开始执行关闭,一直到onDetach,

然后RedFragment开始onCreateView一直执行到onResume,呈现出画面.