getParent().requestDisallowInterceptTouchEvent(true)剝奪父view 對touch 事件的處理權

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;
     }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章