[英]Scroll ViewPager's RecyclerView when page gets scrolled
I have a ViewPager with a couple of RecyclerViews as pages. 我有一个ViewPager,其中有几个RecyclerViews作为页面。 I would like to implement functionality where RecyclerViews which are on other pages move by certain amount after user starts scrolling pages. 我想实现以下功能:用户开始滚动页面后,其他页面上的RecyclerViews移动一定量。
@Override
public void onPageScrolled(int position, float offset, int offsetPx) {
RecyclerView view1 = getPage(position - 1);
RecyclerView view2 = getPage(position + 1);
if(scrollNeeded()) {
view1.scrollBy(0, 200);
view2.scrollBy(0, 200);
}
}
The problem which I have is that everything works fine if I scroll slowly through my ViewPager but if I scroll crazy fast, some RecyclerViews don't get scrolled. 我的问题是,如果我在ViewPager中缓慢滚动,一切都会正常,但是如果我快速滚动,某些RecyclerView不会滚动。 I guess I somehow need to synchronize this method. 我想我需要以某种方式同步此方法。
Any idea how to solve this problem? 任何想法如何解决这个问题? User shouldn't see that scroll. 用户不应看到该滚动。
ViewPager
keeps +1 page left and right preloaded. ViewPager
保持+1页的左右预加载。 Which means 意思是
When user swipes really fast through pages, there is a real case where the page (your RecyclerView
instance and its adapter) are still preparing, so they miss the scrollBy()
call. 当用户真正快速浏览页面时,确实存在页面(您的RecyclerView
实例及其适配器)仍在准备中的情况,因此他们错过了scrollBy()
调用。
You can solve this in different ways. 您可以用不同的方法解决此问题。
Easiest is increasing the number of cached off screen pages (eg 3) by calling viewPager.setOffscreenPageLimit(3)
- for more ViewPager.setOffScreenPageLimit(int) . 最简单的方法是通过调用viewPager.setOffscreenPageLimit(3)
-以获得更多ViewPager.setOffScreenPageLimit(int)来增加屏幕外缓存页面的数量(例如3 ) 。 If you rely on page refreshes every time user swipes, this might be an issue. 如果您每次用户滑动时都依靠页面刷新,则可能是一个问题。
Another option is creating a custom view for your RecyclerView
page and adding a scroll value to be set from outside, eg 另一个选择是为您的RecyclerView
页面创建一个自定义视图,并添加一个滚动值以从外部进行设置,例如
// in your custom page view private RecyclerView.Adapter adapter; private boolean needToScroll; public void setNeedToScroll(boolean needToScroll) { this.needToScroll = needToScroll; // if adapter is not null (ie already set), scroll as is // and set the value to false if (adapter != null) { this.needToScroll = false; scrollBy(0, 200); } } // and then in the place where you define your adapter, but after setting it if (needToScroll) { needToScroll = false; scrollBy(0, 200); }
Finally your view pager scroll listener 最后,您的视图分页器滚动侦听器
@Override public void onPageScrolled(int position, float offset, int offsetPx) { if(scrollNeeded()) { Page view1 = getPage(position - 1); Page view2 = getPage(position + 1); view1.needToScroll(true); view2.needToScroll(true); } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.