How to determine when Fragment becomes visible in ViewPager

后端 未结 26 1743
心在旅途
心在旅途 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:57

    Only this worked for me!! and setUserVisibleHint(...) is now deprecated (I attached docs at end), which means any other answer is deprecated ;-)

    public class FragmentFirewall extends Fragment {
        /**
         * Required cause "setMenuVisibility(...)" is not guaranteed to be
         * called after "onResume()" and/or "onCreateView(...)" method.
         */
        protected void didVisibilityChange() {
            Activity activity = getActivity();
            if (isResumed() && isMenuVisible()) {
                // Once resumed and menu is visible, at last
                // our Fragment is really visible to user.
            }
        }
    
        @Override
        public void onResume() {
            super.onResume();
            didVisibilityChange();
        }
    
        @Override
        public void setMenuVisibility(boolean visible) {
            super.setMenuVisibility(visible);
            didVisibilityChange();
        }
    }
    

    Tested and works with NaviagationDrawer as well, there isMenuVisible() will always return true (and onResume() seems enough, but we want to support ViewPager too).

    setUserVisibleHint is deprecated. If overriding this method, behavior implemented when passing in true should be moved to Fragment.onResume(), and behavior implemented when passing in false should be moved to Fragment.onPause().

提交回复
热议问题