如何测试片段视图是否对用户可见? [英] How to test if a fragment view is visible to the user?

查看:27
本文介绍了如何测试片段视图是否对用户可见?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ViewPager,每个页面都是一个 Fragment 视图.我想测试一个片段是否在可见区域.Fragment.isVisible 仅测试

I have a ViewPager, each page is a Fragment view. I want to test if a fragment is in a visible region. the Fragment.isVisible only test

  • 片段附加到活动
  • 片段设置为可见
  • 片段已添加到视图中

ViewPager 将创建 3 个(默认情况下)fragment,并且它们三个都满足上述条件,但只有一个对用户(人的眼睛)实际可见

The ViewPager will create 3 (by default) fragment and all three of them meet the above criteria, but only one is actually visible to the user (the human eyes)

推荐答案

你说得对,有更好的方法来做到这一点!

在线查看 FragmentPagerAdapter javadoc你会看到有一个方法 setPrimaryItem(ViewGroup container, int position, Object object):void 做你需要的.

Have a look at the FragmentPagerAdapter javadoc online and you'll see there is a method setPrimaryItem(ViewGroup container, int position, Object object):void doing exactly what you need.

来自 javadoc

public void setPrimaryItem(ViewGroup 容器,int 位置,Object 对象)

public void setPrimaryItem (ViewGroup container, int position, Object object)

调用以通知适配器当前考虑哪个项目是主要的",即作为当前显示给用户的页面.

Called to inform the adapter of which item is currently considered to be the "primary", that is the one show to the user as the current page.

Parameters container 包含页面的 View移除.position 现在是主要的页面位置.object 由instantiateItem(View,整数).

Parameters container The containing View from which the page will be removed. position The page position that is now the primary. object The same object that was returned by instantiateItem(View, int).

滚动状态注意

现在,如果您实现此功能并开始调试以了解此功能的确切调用时间,您会很快注意到在准备片段和用户滑动时多次触发此功能.

Now if you implement this and start debugging to get a feel of when exactly this is called you'll quickly notice this is triggered several times on preparing the fragment and while the user is swiping along.

所以附加一个 ViewPager.OnPageChangeListener 并且仅在 viewpagers 滚动状态变为 SCOLL_STATE_IDLE.

So it might be a good idea to also attach a ViewPager.OnPageChangeListener and only do what has to be done once the viewpagers scroll state becomes SCOLL_STATE_IDLE again.

这篇关于如何测试片段视图是否对用户可见?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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