如需转载,请标明原文出处: https://juejin.cn/post/6844903872381583367 ,谢谢。
背景
最近项目首页是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);
}
}