Android:RecyclerView内嵌套RecyclerView导致外层item点击不响应

我是用BaseRecyclerViewAdapterHelper时,recyclerView嵌套一个显示图片的recyclerView,外层recyclerView需要响应item的点击进行跳转,在嵌套的RecyclerView中点击无效。没用原生的Adapter写过,不知道会不会响应。

首先,需要知道触摸事件的响应机制是怎么样的:由上至下,最下层不消费后,则由下至上;然后需要了解一下这三个方法:dispatchTouchEvent、onInterceptTouchEvent、onTouchEvent。

dispatchTouchEvent:事件分发,一般不处理,返回false,事件到onInterceptTouchEvent中处理。

onInterceptTouchEvent:事件拦截,返回true的话,则不向下传递,事件到onTouchEvent,返回false事件往下传递

onTouchEvent:返回true代表事件消费,返回false不消费,事件往上传递。

那么在我只需要内部RecyclerView用于显示,不需要任何操作的情况下,为了使外层RecyclerView的item响应,把嵌入的RecyclerView触摸事件拦截,并且不消费就行了,事件就会传递到上一层,重写嵌套的RecyclerView。

public class NoTouchRecyclerView extends RecyclerView {
    public NoTouchRecyclerView(Context context) {
        super(context);
    }

    public NoTouchRecyclerView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public NoTouchRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
    @Override
    public boolean onTouchEvent(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent e) {
        return true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        return super.dispatchTouchEvent(ev);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_27454233/article/details/103834325