In my application, I have a ViewPager which holds many swipeable Tabs with Fragments inside. I use the setUserVisibleHint
method to detect when a Fragment
comes to the screen. This works great when the user swipes between tabs but it does not work on the first load. To run the code in the method I have to swipe to left and then back to the first Fragment
because the setUserVisibleHint
method is called before the onCreateView
method.
Do you have any ideas how I can run this code after the first Fragment is visible? Is there a method in the ViewPager
or something else?
fragment:fragment:1.1. 0 you can just use onPause() and onResume() to determine which fragment is currently visible for the user. onResume() is called when the fragment became visible and onPause when it stops to be visible. To enable this behavior in the first ViewPager you have to pass FragmentPagerAdapter.
Layout manager that allows the user to flip left and right through pages of data. You supply an implementation of a PagerAdapter to generate the pages that the view shows. ViewPager is most often used in conjunction with android.
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
You can't (and shouldn't) rely on setUserVisibleHint
for this. Instead, you should be using a ViewPager.OnPageChangeListener to get callbacks for when a page becomes visible. E.g.
viewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // do your work } });
Note: You can use ViewPager.SimpleOnPageChangeListener
if you don't need to listen for all callbacks.
setOnPageChangeListener
method is now deprecated, use addOnPageChangeListener
instead
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { @Override public void onPageSelected(int position) { // do your work } });
BELOW WORKED FOR ME
Please create a global view like this
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 In OnResume method
@Override public void onResume() { super.onResume(); if (!getUserVisibleHint()) { return; } //do your stuff here }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With