Search code examples
androidandroid-fragmentsandroid-viewpager

setUserVisibleHint method is called before the onCreateView method and does not work on the first load


I am using this method but it is not working for first fragment but on swiping from second to first fragment it working fine. please help me in this. thanks

 @Override
     public void setUserVisibleHint(boolean isVisibleToUser) 
   {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){   //do Something 
       }
     }

Solution

  • This is how it works

    View view;
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState)
        {
            //inflate view layout
            view =inflater.inflate(R.layout.your_fragment, container, false);
    
            // return view
            return view;
        }
    

    and use this

    @Override
            public void setUserVisibleHint(boolean isUserVisible)
            {
                super.setUserVisibleHint(isUserVisible);
               // when fragment visible to user and view is not null then enter here.
                    if (isUserVisible && view != null)
                    {
                       onResume();
                    }
    
            }
    

    and inside onResume put this code

    @Override
             public void onResume() { 
             super.onResume();   
                if (!getUserVisibleHint()) {
                return;
              }
          //do your stuff here
       }