1

I use ViewPager to store fragments and I just want to download data when I come to this fragment, so I do like this

public abstract class ModelFragment extends Fragment {
    
        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,Bundle savedInstanceState) {
            if(getUserVisibleHint()){ // fragment is visible
                loadData();
            }
            return super.onCreateView(inflater, container, savedInstanceState);
        }
    
        @Override
        public void setUserVisibleHint(boolean isVisibleToUser) {
            super.setUserVisibleHint(isVisibleToUser);
            if (isVisibleToUser && isResumed()) { 
                loadData();
            }
        }
    
        public void loadData(){
            // data for fragment when it visible here
        }
    }

But now in androidx, setUserVisibleHint is deprecated so what is the best solution here?

Thang
  • 409
  • 1
  • 6
  • 17
  • 1
    please check this https://stackoverflow.com/questions/57885849/in-androidx-fragment-app-fragment-setuservisiblehint-is-deprecated-and-not-exec – Nour Eldien Mohamed Jul 16 '20 at 07:24

1 Answers1

1

You can use onResume and onPause methods instead of setUserVisibleHint. For this you have to change default behaviour in FragmentPagerAdapter constructor.

FragmentPagerAdapter(fragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)

Checkout this https://developer.android.com/reference/androidx/fragment/app/FragmentPagerAdapter#BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT

Abid Khan
  • 2,451
  • 4
  • 22
  • 45