viewpager+fragment获取fragment是否可见的状态

前言:近日根据项目需求,需要获取到viewpager+fragment中某个fragment的可见状态。但是fragment的OnResume()和OnPause()方法在切换tab时并不回调,如何才能判断该fragment是否可见呢?

解决办法:

重写setUserVisibleHint方法。

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser) {
            //相当于OnResume(),可以做相关逻辑
        }else {
            //相当于OnPause()
        }
    }

Fragment的生命周期

viewpager+fragment中调用setUserVisibleHint的fragment的生命周期:

1   E/myfragment: setUserVisibleHint=false
2   E/myfragment: onAttach
3   E/myfragment: onCreate
4   E/myfragment: onCreateView
5   E/myfragment: onActivityCreated
6   E/myfragment: onStart
7   E/myfragment: onresume
8   E/myfragment: setUserVisibleHint=true   //该fragment可见时
9   E/myfragment: setUserVisibleHint=false  //该fragment不可见时
10  E/myfragment: onPause                   
11  E/myfragment: onStop
12  E/myfragment: onDestroyView
13  E/myfragment: onDestroy
14  E/myfragment: onDetach

说明:1-7生命周期是fragment初始化并加载到viewpager中时执行的。10-14是viewpager所在的activity被销毁过程中,fragment的生命周期执行过程。8是切换到该fragment可见时,9是该fragment不可见时。
使用FragmentPagerAdapter+ViewPager时,切换回上一个Fragment页面时(已经初始化完毕),不会回调任何生命周期方法以及onHiddenChanged(),只有setUserVisibleHint(boolean isVisibleToUser)会被回调。

分析setUserVisibleHint方法

/**
* Set a hint to the system about whether this fragment's UI is currently visible
* to the user. This hint defaults to true and is persistent across fragment instance
* state save and restore.
*
* 

An app may set this to false to indicate that the fragment's UI is * scrolled out of visibility or is otherwise not directly visible to the user. * This may be used by the system to prioritize operations such as fragment lifecycle updates * or loader ordering behavior.

* *

Note: This method may be called outside of the fragment lifecycle. * and thus has no ordering guarantees with regard to fragment lifecycle method calls.

* * @param isVisibleToUser true if this fragment's UI is currently visible to the user (default), * false if it is not. */ public void setUserVisibleHint(boolean isVisibleToUser) { if (!mUserVisibleHint && isVisibleToUser && mState < STARTED && mFragmentManager != null && isAdded()) { mFragmentManager.performPendingDeferredStart(this); } mUserVisibleHint = isVisibleToUser; mDeferStart = mState < STARTED && !isVisibleToUser; }

并参考以下资料:
Fragment 中setUserVisibleHint方法不执行
stackoverflow
我们可以知道,在单个fragment中是不会被系统调用setUserVisibleHint方法的。

另附:onHiddenChanged的回调时机

当使用add()+show(),hide()跳转新的Fragment时,旧的Fragment回调onHiddenChanged(),不会回调onStop()等生命周期方法,而新的Fragment在创建时是不会回调onHiddenChanged()。

参考资料:Fragment全解析系列(二):正确的使用姿势。

你可能感兴趣的:(源码分析)