确定在ViewPager中当前可见的片段 [英] Determine which fragment currently visible in ViewPager

查看:88
本文介绍了确定在ViewPager中当前可见的片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有ViewPager,用于显示一些片段,我的FragmentActivity上也有TextView.我需要根据当前在ViewPager中选择的片段来更改TextView中的文本.我遇到的问题:ViewPager具有某种缓存机制,它会在对用户真正可见之前实例化片段,例如,当我在第三页的ViewPager片段中选择第二页时.而且,我无法确定片段内部是否可见该片段,或者该片段只是由ViewPager创建的,但对于用户而言并非真正可见.我曾尝试使用OnPageChangeListener进行此操作,但是对我而言,对其进行的更改太慢了(滚动页面,然后我的TextView更改了)

我实际需要的内容:我需要确定当前在ViewPager中可见的片段,无论是FragmentActivity还是Fragment本身.我怎样才能做到这一点?

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.OnPageChangeListener是此处的明显方法.正如您所注意到的,在页面居中之前,onPageSelected(int position)不会被调用(如果您通过触摸并按住不放来缓慢滚动页面).

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).

我实际需要的是:无论是通过FragmentActivity还是从Fragment本身,我都需要确定ViewPager中当前可见的片段.我该如何实现?

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中,在两页之间滑动时都可以看到两页,因此中间滑动时当前可见"是哪一页?我的假设是,您将把更可见"的页面视为当前可见".

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.

这篇关于确定在ViewPager中当前可见的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆