I've ViewPager
which I'm using for displaying few fragments, I also have TextView
on my FragmentActivity
. I need to change text in TextView
depending on which fragment is currently selected in ViewPager
. The problem I've faced: ViewPager
have some caching mechanism, it instantiates fragments before they are really visible for user, for example when I select second page in ViewPager
fragment on third page also created. What is more I can't determine inside fragment is this fragment visible now or it's just created by ViewPager
, but not really visible for user. I've tryed to use OnPageChangeListener
for this, but changes made in it was unacceptable slow for me(page scrolled and then my TextView
have changed)
What I actually need: I need to determine which fragment is currently visible in ViewPager
, no matter from FragmentActivity
or from Fragment
itself. How can I achieve this?
ViewPager save Fragment in FragmentManager with particular tags, So We can get ViewPager's fragment by FragmentManager class by providing tag. And ViewPager provide tag to each fragment by following syntax : Fragment page = getSupportFragmentManager(). findFragmentByTag("android:switcher:" + R.
In ViewPager2 and ViewPager from version androidx. fragment:fragment:1.1. 0 you can just use onPause and onResume callbacks to determine which fragment is currently visible for the user. onResume callback is called when fragment became visible and onPause when it stops to be visible.
You can use findFragmentByTag() or findFragmentById() functions to get a fragment. If mentioned methods are returning null then that fragment does not exist.
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 .
ViewPager.OnPageChangeListener
is the obvious approach here. And as you have noticed, onPageSelected(int position)
doesn't get called until the page is centered (if you are slowly scrolling the page by touch and holding on).
What I actually need: I need to determine which fragment is currently visible in ViewPager, no matter from FragmentActivity or from Fragment itself. How can I achieve this?
First, you haven't defined "currently visible". In a ViewPager
, 2 pages can both be seen while swiping between them, so which one is "currently visible" mid-swipe? My assumption is that you would consider whichever page is "more visible" to be "currently visible".
Having that said, I would look into using onPageScrolled (int position, float positionOffset, int positionOffsetPixels)
. It appears that positionOffset
may be able to give you the information you need. I would test it with some logging statements to see what data returns.
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