当Recyclerview嵌套recyclerview滑动子布局是本应该是子布局在滑动,现象却是父布局在滑动。出现这种情况的原因就是事件没有分发到子view。解决这个问题就需要了解android事件分发的机制。
Android事件分发机制要研究的对象是MotionEvent即点击事件。点击事件就是手指触摸到屏幕出现的一系列事件
ACTION_DOWN:手指刚接触到屏幕
ACTION_MOVE:手指在屏幕上移动
ACTION_UP:手指从屏幕上离开的瞬间
点击事件的分发也就是MotionEvent的传递。产生MotionEvent后将其传递给一个具体的View.
public boolean dispatchTouchEvent(MotionEvent ev)
用来进行事件的分发。如果事件能够传递给当前View,那么此方法一定会被调用,返回的结果受当前View的onTouchEvent和下级View的dispatchTouchEvent方法影响,表示是否消耗当前事件。
public boolean onInterceptTouchEvent(MotionEvent ev)
在dispatchTouchEvent(MotionEvent ev)方法内部调用,用来判断是否拦截某个事件,那么在同一个事件系列当中,此方法不会被再次调用,返回结果表示是否拦截当前事件。
public boolean onTouchEvent(MotionEvent ev)
在dispatchTouchEvent(MotionEvent ev)方法中调用,用来处理点击事件,返回的结果表示是否消耗当前事件,如锅不消耗,这在同一个事件系列中,当前View无法再接收到事件。
当一个点击事件产生后,他的传递顺序是Activity->window->view.事件经过activity window,传给顶级view,顶级view再将事件按照传递规则传给子view
通过以上了解基本知道子Recyclerview不会滑动是因为父Recyclerview消耗了点击事件。所以要解决该问题就是让父Recyclerview将事件传递下来。
1.自定义父Recyclerview让其不要拦截事件。
重写onInterceptTouchEvent()方法。`public class ParentRecyclerView extends RecyclerView {
public ParentRecyclerView(@NonNull Context context) {
super(context);
}
public ParentRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ParentRecyclerView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
//return false 不拦截,继续分发下去
@Override
public boolean onInterceptTouchEvent(MotionEvent e) {
return false;
}
}`
2.重写子Recyclerview请求父Recyclerview将事件分发下来。
重写dispatchTouchEvent()方法,通知通知父Recyclerview不要拦截点击事件
public class ChildRecyclerview extends RecyclerView {
public ChildRecyclerview(@NonNull Context context) {
super(context);
}
public ChildRecyclerview(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public ChildRecyclerview(@NonNull Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//通知父层ViewGroup不要拦截点击事件
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
}
3.通过OnTouchListener来告诉父布局,不要拦截事件
holder.bigFileRecyclerView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
view.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
view.getParent().requestDisallowInterceptTouchEvent(false);
break;
default:
break;
}
return false;
}
});
Android事件分发机制还是很复杂的一个机制,这只是冰山一角,想要继续了解还是要继续学习,继续研究。