Bersh
Bersh

Reputation: 2809

Determine which fragment currently visible in ViewPager

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?

Upvotes: 8

Views: 7567

Answers (1)

Steven Byle
Steven Byle

Reputation: 13269

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.

Upvotes: 7

Related Questions