Parent RecyclerView 拾取原本用于嵌套 RecyclerView 的手势

Parent RecyclerView picks up gestures that were intended to be for the nested RecyclerView

我有一个垂直 RecyclerView 和一个嵌套的水平 RecyclerView 作为其子项之一。内部视图用作带有 PagerSnapHelper 的图像轮播。当我尝试水平滚动内部视图时,我的行为不太理想。有时,即使我的意图是水平滚动内部视图,父视图也会拿起手势并垂直滚动。有没有办法配置默认滚动检测器,使水平滚动更平滑?

您可以尝试将此 RecyclerViewoverriden method 一起用作父项 RecyclerView:

public class CustomRecyclerView extends RecyclerView {

    private int mTouchSlop;
    private float mPrevX;

    public CustomRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        switch (e.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPrevX = MotionEvent.obtain(e).getX();
                break;

            case MotionEvent.ACTION_MOVE:
                final float eventX = e.getX();
                float xDiff = Math.abs(eventX - mPrevX);

                if (xDiff > mTouchSlop) {
                    return false;
                }
        }

        return super.onInterceptTouchEvent(e);
    }
}

xml

中的示例
<com.example.Whosebug.CustomRecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

下面的方法试图在触摸嵌套的 recyclerview 时禁用父 recyclerview 的触摸事件。

    nestedRecyclerView.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch (View v, MotionEvent event){
    int action = event.getAction();
    switch (action) {
        case MotionEvent.ACTION_DOWN:
            // Disallow parent to intercept touch events.
            v.getParent().requestDisallowInterceptTouchEvent(true);
            break;

        case MotionEvent.ACTION_UP:
            // Allow parent to intercept touch events.
            v.getParent().requestDisallowInterceptTouchEvent(false);
            break;
    }

    // Handle inner(child) touch events.
    v.onTouchEvent(event);
    return true;
}
});