getParent().requestDisallowInterceptTouchEvent(true)剥夺父view 对touch 事件的处理权

来源:互联网 发布:日语笔译知乎 编辑:程序博客网 时间:2024/05/01 08:57

android 事件处理机制之requestDisallowInterceptTouchEvent

夺取ViewPager的左右滑动requestDisallowInterceptTouchEvent

探究requestDisallowInterceptTouchEvent失效的原因

在开发过程中可能会遇到诸如此类问题:

1、在上下滑动的ScrollView中嵌套一个横滑列表,拖动横滑列表时可能引起ScrollView的上下滑动导致体验极差

2、在ViewPager中嵌套了一个横滑列表,在拖动横滑列表时同样可能导致ViewPager的tab切换。

requestDisallowInterceptTouchEvent 是ViewGroup类中的一个公用方法,参数是一个boolean值,官方介绍如下

when a child does not want this parent and its ancestors to intercept touch events with ViewGroup.onInterceptTouchEvent(MotionEvent).

This parent should pass this call onto its parents. This parent must obey this request for the duration of the touch (that is, only clear the flag after this parent has received an up or a cancel.

android系统中,一次点击事件是从父view传递到子view中,每一层的view可以决定是否拦截并处理点击事件或者传递到下一层,如果子view不处理点击事件,则该事件会传递会父view,由父view去决定是否处理该点击事件。在子view可以通过设置此方法去告诉父view不要拦截并处理点击事件,父view应该接受这个请求直到此次点击事件结束。

实际的应用中,可以在子view的ontouch事件中注入父ViewGroup的实例,并调用requestDisallowInterceptTouchEvent去阻止父view拦截点击事件

public boolean onTouch(View v, MotionEvent event) {     ViewGroup viewGroup = (ViewGroup) v.getParent();     switch (event.getAction()) {     case MotionEvent.ACTION_MOVE:         viewGroup.requestDisallowInterceptTouchEvent(true);         break;     case MotionEvent.ACTION_UP:     case MotionEvent.ACTION_CANCEL:         viewGroup .requestDisallowInterceptTouchEvent(false);         break;     }}
0 0