Fragment(1)-生命周期方法与Fragment视图是否可见间的细节

来源:互联网 发布:医疗器械软件测试报告 编辑:程序博客网 时间:2024/05/22 03:11

前言

根据ViewPager+Frgment的小例子,来研究Fragment生命周期方法与Fragment视图是否可见间的细节。

正文

所用资源:ViewPager+Fragment,ViewPager只默认预加载1页,共三个Fragment。

动作1:执行App,界面显示

//PlaceholderFragment: 1 setUserVisibleHint() called with: isVisibleToUser = [false]//PlaceholderFragment: 2 setUserVisibleHint() called with: isVisibleToUser = [false]//PlaceholderFragment: 1 onAttach() called with: //PlaceholderFragment: 1 onCreate() called with: //PlaceholderFragment: 1 setUserVisibleHint() called with: isVisibleToUser = [true]//PlaceholderFragment: 1 onCreateView() called with://PlaceholderFragment: 1 onViewCreated() called with://PlaceholderFragment: 1 onActivityCreated() called with://PlaceholderFragment: 1 onStart() called with://PlaceholderFragment: 1 onResume() called with://PlaceholderFragment: 2 onAttach() called with: //PlaceholderFragment: 2 onCreate() called with: //PlaceholderFragment: 2 onCreateView() called with://PlaceholderFragment: 2 onViewCreated() called with://PlaceholderFragment: 2 onActivityCreated() called with://PlaceholderFragment: 2 onStart() called with://PlaceholderFragment: 2 onResume() called with:

首先,会调用前两页的setUserVisibleHint()方法并设置为false,表明两个Fragmnet所代表的视图,还尚未显示。

接着执行Fragment1的生命周期流程,并在onCreate()与onCreateView()之间执行setUserVisbleHint()为true,来表示Fragment1已用户可见。

随后执行Fragment2的生命周期流程,直至onResume()被调用。但是此时Fragment2还处于用户不可见状态。

动作2:滑动到第二个Fragment

//PlaceholderFragment: 3 setUserVisibleHint() called with: isVisibleToUser = [false]//PlaceholderFragment: 1 setUserVisibleHint() called with: isVisibleToUser = [false]//PlaceholderFragment: 2 setUserVisibleHint() called with: isVisibleToUser = [true]//PlaceholderFragment: 3 onAttach() called with://PlaceholderFragment: 3 onCreate() called with://PlaceholderFragment: 3 onCreateView() called with://PlaceholderFragment: 3 onViewCreated() called with://PlaceholderFragment: 3 onActivityCreated() called with://PlaceholderFragment: 3 onStart() called with://PlaceholderFragment: 3 onResume() called with:

首先,执行3个Fragment的setUserVisbleHint()方法,去表明Fragment是否为可见状态。此时,Fragment2处于可见状态,Fragment1和预加载的Fragment3处于不可见状态。

紧接着再去执行Fragment3的生命周期方法。

动作3:滑动到第三个Fragment

//PlaceholderFragment: 2 setUserVisibleHint() called with: isVisibleToUser = [false]//PlaceholderFragment: 3 setUserVisibleHint() called with: isVisibleToUser = [true]//PlaceholderFragment: 1 onPause() called with://PlaceholderFragment: 1 onStop() called with://PlaceholderFragment: 1 onDestroyView() called with:

首先,先执行当前Fragment和缓存Fragmnet2的setUserVisibleHint()方法,表明各自的可见状态,此时,Fragment3处于可见状态。

紧接着去释放Fragment1的视图资源,但并不销毁Fragment1

结论

Fragment和Activity的大部分生命周期绑定在一起,但是Fragment的onResume()并不意味着Fragment对于用户可见,真正Fragment对用户可见会执行的方法是setUserVisbleHInt()并且为true时。

在Fragment的声明周期中,setUserVisbleHint()方法会被调用两次,第一次是在Fragment声明周期尚未开始时,用于初始化userVisbleHint变量;第二次实在onCreate()与onCreateView()之间调用,表明Fragment已经处于可见状态。

2 0
原创粉丝点击