項目中最近把viewpager+fragment+recyclerview來實(shí)現(xiàn)首頁,但是最近更換為viewpager2后掌呜,發(fā)現(xiàn)一些手勢沖突的問題
1.fragment上下滑動異常靈敏,稍有左右偏移便會翻頁
2.與recyclerview有滑動沖突問題
我的解決方法如下:
1.重新設(shè)置viewpager2的滑動靈敏度
try {
final Field recyclerViewField = ViewPager2.class.getDeclaredField("mRecyclerView");
recyclerViewField.setAccessible(true);
final RecyclerView recyclerView = (RecyclerView) recyclerViewField.get(vp_rec_pager);
final Field touchSlopField = RecyclerView.class.getDeclaredField("mTouchSlop");
touchSlopField.setAccessible(true);
final int touchSlop = (int) touchSlopField.get(recyclerView);
touchSlopField.set(recyclerView, touchSlop * 4);//6 is empirical value
} catch (Exception ignore) {
}
2.重寫recyclerview進(jìn)行內(nèi)部攔截手勢:
public class RecyclerviewAtViewPager2 extends RecyclerView {
public RecyclerviewAtViewPager2(@NonNull Context context) {
super(context);
}
public RecyclerviewAtViewPager2(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public RecyclerviewAtViewPager2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private int startX, startY;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) ev.getX();
startY = (int) ev.getY();
getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_MOVE:
int endX = (int) ev.getX();
int endY = (int) ev.getY();
int disX = Math.abs(endX - startX);
int disY = Math.abs(endY - startY);
if(disX > disY){
getParent().requestDisallowInterceptTouchEvent(canScrollHorizontally(startX -endX));
}else {
getParent().requestDisallowInterceptTouchEvent(canScrollVertically(startY -endY));
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return super.dispatchTouchEvent(ev);
}
}