How to know if a Fragment is Visible?

前端 未结 10 1905
闹比i
闹比i 2020-12-01 06:07

I\'m using the support library v4 and my questions are, How to know if a Fragment is Visible? and How can I change the propierties of the Layout inflated in the Fragment? Th

相关标签:
10条回答
  • 2020-12-01 06:34

    None of the above solutions worked for me. The following however works like a charm:-

    <code>override fun setUserVisibleHint(isVisibleToUser: Boolean)</code>
    
    0 讨论(0)
  • 2020-12-01 06:35

    If you want to know when use is looking at the fragment you should use

    yourFragment.isResumed()
    

    instead of

    yourFragment.isVisible()
    

    First of all isVisible() already checks for isAdded() so no need for calling both. Second, non-of these two means that user is actually seeing your fragment. Only isResumed() makes sure that your fragment is in front of the user and user can interact with it if thats whats you are looking for.

    0 讨论(0)
  • 2020-12-01 06:35

    One thing to be aware of, is that isVisible() returns the visible state of the current fragment. There is a problem in the support library, where if you have nested fragments, and you hide the parent fragment (and therefore all the children), the child still says it is visible.

    isVisible() is final, so can't override unfortunately. My workaround was to create a BaseFragment class that all my fragments extend, and then create a method like so:

    public boolean getIsVisible()
    {
        if (getParentFragment() != null && getParentFragment() instanceof BaseFragment)
        {
            return isVisible() && ((BaseFragment) getParentFragment()).getIsVisible();
        }
        else
        {
            return isVisible();
        }
    }
    

    I do isVisible() && ((BaseFragment) getParentFragment()).getIsVisible(); because we want to return false if any of the parent fragments are hidden.

    This seems to do the trick for me.

    0 讨论(0)
  • 2020-12-01 06:42

    getUserVisibleHint() comes as true only when the fragment is on the view and visible

    0 讨论(0)
提交回复
热议问题