转载请标明出处:juejin.im/post/5d0c76… ,谢谢。bash
最近项目首页是ViewPager+Fragment实现左右滑动切换,而且其中有轮播图,目前轮播图是用RecyclerView来实现。
原本是一切正常,后来增长一个需求,须要轮播图能够无限滑动。
首先就想到在RecyclerView.Adapter#getItemCount()方法返回Integer.MAX_VALUE,而后在稍微修改下List.get(int index)取值逻辑,最后页面打开让RecyclerView滚动到中间来实现。ide
在RecyclerView.Adapter#getItemCount()返回真正的List.size()数量的时候一切正常,RecyclerView 、ViewPager两个相安无事,很是和谐。可是当RecyclerView.Adapter#getItemCount()返回Integer.MAX_VALUE,就会致使RecyclerView左右滑动和ViewPager的左右滑动冲突。post
目前测试出两个解决方案:测试
RecyclerView.Adapter#getItemCount()不要返回Integer.MAX_VALUE,改成返回3000000(这个数值可自行测试得出)或者其余数值。
测试机有限,目前测试返回390W+的时候均可以正常滑动,一旦返回大于等于400W就会开始冲突。
具体缘由未知。
这样能够不须要自定义RecyclerViewui
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);
}
}
复制代码