1. 程式人生 > >帶下拉重新整理的RecyclerView巢狀橫向RecyclerView事件衝突

帶下拉重新整理的RecyclerView巢狀橫向RecyclerView事件衝突

實際效果圖

採用結構

  • PtrFrameLayout 巢狀一個帶下拉重新整理的RecyclerViewPtrFrameLayout是一個自定義下拉重新整理佈局

  • RV內部Item包含一個橫向滑動的RecyclerView在頂部

導致的問題:橫向滑動RecyclerView時經常容易引起下拉重新整理,這種體驗很差

解決思路

  1. 繼承RecyclerView,重寫dispatchTouchEvent,根據ACTION_MOVE的方向判斷是否呼叫getParent().requestDisallowInterceptTouchEvent去阻止父view攔截點選事件

  2. 通過繼承PtrFrameLayout,重寫requestDisallowInterceptTouchEvent方法,獲取disallowIntercept來判斷是否分發事件給父View(避免父View獲取事件引起下拉操作)

    @Override
    public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
        disallowInterceptTouchEvent = disallowIntercept;
        //子View告訴父容器不要攔截我們的事件的
        super.requestDisallowInterceptTouchEvent(disallowIntercept);
    }```

#### 具體原始碼
* 重寫橫向滑動RecyclerView

public class BetterRecyclerView extends RecyclerView { private ViewGroup parent;

public BetterRecyclerView(Context context) {
    super(context);
}

public BetterRecyclerView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

public void setNestParent(ViewGroup parent) {
    this.parent = parent;
}

private int lastX = -1; private int lastY = -1;

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    int x = (int) ev.getRawX();
    int y = (int) ev.getRawY();
    int dealtX = 0;
    int dealtY = 0;

    switch (ev.getAction()) {
        case MotionEvent.ACTION_DOWN:
            dealtX = 0;
            dealtY = 0;
            // 保證子View能夠接收到Action_move事件
            getParent().requestDisallowInterceptTouchEvent(true);
            break;
        case MotionEvent.ACTION_MOVE:
            dealtX += Math.abs(x - lastX);
            dealtY += Math.abs(y - lastY);

// Log.i("dispatchTouchEvent", "dealtX:=" + dealtX); // Log.i("dispatchTouchEvent", "dealtY:=" + dealtY); // 這裡是夠攔截的判斷依據是左右滑動,讀者可根據自己的邏輯進行是否攔截 if (dealtX >= dealtY) { getParent().requestDisallowInterceptTouchEvent(true); } else { getParent().requestDisallowInterceptTouchEvent(false); } lastX = x; lastY = y; break; case MotionEvent.ACTION_CANCEL: break; case MotionEvent.ACTION_UP: break;

    }
    return super.dispatchTouchEvent(ev);
}
* 重寫PtrFrameLayout的部分原始碼

private boolean disallowInterceptTouchEvent = false; @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { disallowInterceptTouchEvent = disallowIntercept;

    super.requestDisallowInterceptTouchEvent(disallowIntercept);
}

@Override
public boolean dispatchTouchEvent(MotionEvent e) {
    switch (e.getAction()) {
        case MotionEvent.ACTION_UP:
            this.requestDisallowInterceptTouchEvent(false);
            disableWhenHorizontalMove(true);
            break;
    }
    if (disallowInterceptTouchEvent) {
        return dispatchTouchEventSupper(e);
    }
    return super.dispatchTouchEvent(e);
}

作者:天才小迷弟 連結:https://www.jianshu.com/p/3868f0cbffe1 來源:簡書 簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。