How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1735
心在旅途
心在旅途 2020-11-22 00:24

Problem: Fragment onResume() in ViewPager is fired before the fragment becomes actually visible.

For example, I have 2 fragments with

26条回答
  •  春和景丽
    2020-11-22 00:43

    I encountered the same problem while working with FragmentStatePagerAdapters and 3 tabs. I had to show a Dilaog whenever the 1st tab was clicked and hide it on clicking other tabs.

    Overriding setUserVisibleHint() alone didn't help to find the current visible fragment.

    When clicking from 3rd tab -----> 1st tab. It triggered twice for 2nd fragment and for 1st fragment. I combined it with isResumed() method.

        @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
    
        // Make sure that fragment is currently visible
        if (!isVisible && isResumed()) {
            // Call code when Fragment not visible
        } else if (isVisible && isResumed()) {
           // Call code when Fragment becomes visible.
        }
    
    }
    

提交回复
热议问题