Fragment lifecycle - which method is called upon show / hide?

前端 未结 11 1005
伪装坚强ぢ
伪装坚强ぢ 2020-12-04 08:31

I am using the following method to switch between Fragments (in my NavigationDrawer) by showing / hiding them.

protected void showFragment(int container, Fra         


        
11条回答
  •  [愿得一人]
    2020-12-04 08:59

    Only this worked for me!! and setUserVisibleHint(...) is now deprecated (I attached docs at end), which means some other answers are 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().

提交回复
热议问题