防止 ViewPager 破坏离屏视图 [英] Prevent ViewPager from destroying off-screen views

查看:24
本文介绍了防止 ViewPager 破坏离屏视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 ViewPager 连接到一个显示三个片段的 FragmentPagerAdapter.当 ViewPager 从当前位置滑动不止一次时,它似乎会破坏托管片段的视图.

I have a ViewPager hooked up to a FragmentPagerAdapter that's displaying three fragments. The ViewPager appears to destroy a hosted fragment's view when it is more than one swipe away from the current position.

这些视图都是简单的列表,这种优化完全没有必要,所以我想禁用它.这会导致一些视觉问题,因为列表应用了布局动画,并且这些动画在它们被销毁和重新创建后正在重播.它还每次都显示滚动条介绍动画(滚动条短暂可见以指示可以滚动),这可能会分散注意力,并且用户的当前滚动位置在此过程中丢失.

These views are all simple lists and this optimization is completely unnecessary, so I'd like to disable it. It's causing some visual problems because the lists have layout animations applied to them and those animations are being replayed after they've been destroyed and recreated. It also shows the scrollbar intro animation each time (where the scrollbar is briefly visible to indicate that scrolling is possible) which can be distracting, and the user's current scroll position is lost in the process.

它也不会在第一次滑动发生之前加载第三个片段,这是有问题的,因为每个片段处理自己的服务调用,我更希望在加载活动时同时触发所有三个片段.延迟第三次服务呼叫不太理想.

It also doesn't load the third fragment until the first swipe happens, which is problematic because each fragment handles its own service calls and I'd prefer to have all three fire off at the same time when the activity loads. Having the third service call delayed is less than ideal.

有什么方法可以说服 ViewPager 停止这种行为并将我的所有片段保存在内存中吗?

Is there any way to convince ViewPager to stop this behavior and just keep all my fragments in memory?

推荐答案

修订版 4,向 ViewPager 添加了一个方法,该方法允许您指定要使用的屏幕外页面的数量,而不是默认值 1.

In revision 4 of the Support Package, a method was added to ViewPager which allows you to specify the number of offscreen pages to use, rather than the default which is 1.

在您的情况下,您希望指定 2,这样当您在第三页时,第一个不会被销毁,反之亦然.

In your case, you want to specify 2, so that when you are on the third page, the first one is not destroyed, and vice-versa.

mViewPager = (ViewPager)findViewById(R.id.pager);
mViewPager.setOffscreenPageLimit(2);

这篇关于防止 ViewPager 破坏离屏视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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