For reprint, please indicate the original source: https://juejin.cn/post/6844903872381583367, thank you.
background
Recently, the home page of the project is ViewPager+Fragment to achieve left and right sliding switch, and there is a RecyclerView, currently the RecyclerView is used to achieve the RecyclerView. Everything was fine until a requirement was added that the rotation map could slide indefinitely. Use recyclerView.adapter #getItemCount() to return integer.max_value, and then modify the list.get (int index) logic slightly. Finally, the page opens and RecyclerView scrolls to the middle.
The problem
RecyclerView.Adapter#getItemCount() returns the real list.size () number. However, when recyclerView.adapter #getItemCount() returns integer.max_value, there will be a conflict between RecyclerView and ViewPager sliding left or right.
To solve
Two solutions have been tested:
1. Change the return value
Recyclerview.adapter# getItemCount() do not return integer.max_value, return 3000000(this can be tested) or some other value. The test machine is limited. At present, it can slide normally when the test returns 390W+, and once the return is greater than or equal to 400W, the conflict will start. The exact cause is unknown. This can not need to customize RecyclerView.
2. Customize 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); }}returnsuper.dispatchTouchEvent(event); }}Copy the code