Determine which fragment currently visible in ViewPager

独自空忆成欢 提交于 2019-12-21 01:21:52

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/16221195/determine-which-fragment-currently-visible-in-viewpager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!