RecyclerView 、ViewPager 左右滑动冲突

栏目: IOS · Android · 发布时间: 6年前

内容简介:最近项目首页是ViewPager+Fragment实现左右滑动切换,并且其中有轮播图,目前轮播图是用RecyclerView来实现。本来是一切正常,后来增加一个需求,需要轮播图可以无限滑动。首先就想到在RecyclerView.Adapter#getItemCount()方法返回Integer.MAX_VALUE,然后在稍微修改下List.get(int index)取值逻辑,最后页面打开让RecyclerView滚动到中间来实现。

最近项目首页是ViewPager+Fragment实现左右滑动切换,并且其中有轮播图,目前轮播图是用RecyclerView来实现。

本来是一切正常,后来增加一个需求,需要轮播图可以无限滑动。

首先就想到在RecyclerView.Adapter#getItemCount()方法返回Integer.MAX_VALUE,然后在稍微修改下List.get(int index)取值逻辑,最后页面打开让RecyclerView滚动到中间来实现。

问题

在RecyclerView.Adapter#getItemCount()返回真正的List.size()数量的时候一切正常,RecyclerView 、ViewPager两个相安无事,非常和谐。但是当RecyclerView.Adapter#getItemCount()返回Integer.MAX_VALUE,就会导致RecyclerView左右滑动和ViewPager的左右滑动冲突。

解决

目前测试出两个解决方案:

1. 更改返回值

RecyclerView.Adapter#getItemCount()不要返回Integer.MAX_VALUE,改为返回3000000(这个数值可自行测试得出)或者其他数值。

测试机有限,目前测试返回390W+的时候都可以正常滑动,一旦返回大于等于400W就会开始冲突。

具体原因未知。

这样可以不需要自定义RecyclerView

2. 自定义RecyclerView

public class SlidingConflictRecyclerView extends RecyclerView {

    public SlidingConflictRecyclerView(@NonNull Context context) {
        super(context);
    }

    public SlidingConflictRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public SlidingConflictRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        boolean canScrollHorizontally = canScrollHorizontally(-1) || canScrollHorizontally(1);
        boolean canScrollVertically = canScrollVertically(-1) || canScrollVertically(1);
        if (canScrollHorizontally || canScrollVertically) {
            ViewParent parent = getParent();
            if (parent != null) {
                parent.requestDisallowInterceptTouchEvent(true);
            }
        }
        return super.dispatchTouchEvent(event);
    }

}
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Algorithms and Data Structures

Algorithms and Data Structures

Kurt Mehlhorn、Peter Sanders / Springer / 2008-08-06 / USD 49.95

Algorithms are at the heart of every nontrivial computer application, and algorithmics is a modern and active area of computer science. Every computer scientist and every professional programmer shoul......一起来看看 《Algorithms and Data Structures》 这本书的介绍吧!

html转js在线工具
html转js在线工具

html转js在线工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具