防止 ViewPager 破坏屏幕外视图

Prevent ViewPager from destroying off-screen views(防止 ViewPager 破坏屏幕外视图)
本文介绍了防止 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?

推荐答案

在 revision 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 破坏屏幕外视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to target newer versions in .gitlab-ci.yml using auto devops (java 11 instead of 8 and Android 31 instead of 29)(如何在.gitlab-ci.yml中使用自动开发工具(Java 11而不是8,Android 31而不是29)瞄准较新的版本)
Android + coreLibraryDesugaring: which Java 11 APIs can I expect to work?(Android+core LibraryDesugering:我可以期待哪些Java 11API能够工作?)
How to render something in an if statement React Native(如何在If语句中呈现某些内容Reaction Native)
How can I sync two flatList scroll position in react native(如何在本机Reaction中同步两个平面列表滚动位置)
Using Firebase Firestore in offline only mode(在仅脱机模式下使用Firebase FiRestore)
Crash on Google Play Pre-Launch Report: java.lang.NoSuchMethodError(Google Play发布前崩溃报告:java.lang.NoSuchMethodError)