当页面滚动时,通过滚动ViewPager的RecyclerView来实现页面滑动。

3
我有一个ViewPager,其中包含一些作为页面的RecyclerView。我想要实现的功能是,在用户开始滚动页面后,其他页面上的RecyclerView会移动一定的距离。
@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);
    }
}

我遇到的问题是,如果我通过ViewPager缓慢滚动,一切都可以正常工作,但是如果我疯狂快速滚动,一些RecyclerView将不能被滚动。我猜我需要同步这种方法。
有什么解决这个问题的方法吗?用户不应该看到那个滚动。
1个回答

4

ViewPager会预加载左右各+1页。这意味着:

  • 在一开始时,当前页面和下一页
  • 在最后时,最后一页和前一页
  • 在其他任何位置,当前页、上一页和下一页

当用户快速滑动页面时,有一种情况是页面(你的RecyclerView实例及其适配器)仍在准备中,所以它们无法响应scrollBy()调用。

你可以通过不同的方式解决这个问题。

  1. Easiest is increasing the number of cached off screen pages (e.g. 3) by calling viewPager.setOffscreenPageLimit(3) - for more ViewPager.setOffScreenPageLimit(int). If you rely on page refreshes every time user swipes, this might be an issue.

  2. Another option is creating a custom view for your RecyclerView page and adding a scroll value to be set from outside, e.g.

    // 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 (i.e. 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);
        }
    }
    

有没有想法如何实现这种布局... 我有一个线性布局,在下面有选项卡和视图页面... 现在有两个选项卡,在选项卡中有不同的选项卡中的可回收视图或网格视图... 我希望一旦我开始滚动视图页面的选项卡数据... 它应该从页面顶部滚动,线性布局应该跑出页面,用户只能看到用户定义的内容... 这是可回收视图数据。 - Erum
@Erum 这超出了原始问题的范围。请创建一个新的工单,添加所需布局的截图,很可能会比预期更快地得到答案。 - Dimitar Genov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接