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

在開發過程當中可能會遇到諸如此類問題:android

一、在上下滑動的ScrollView中嵌套一個橫滑列表,拖動橫滑列表時可能引發ScrollView的上下滑動致使體驗極差this

二、在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).get

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.it

android系統中,一次點擊事件是從父view傳遞到子view中,每一層的view能夠決定是否攔截並處理點擊事件或者傳遞到下一層,若是子view不處理點擊事件,則該事件會傳遞會父view,由父view去決定是否處理該點擊事件。在子view能夠經過設置此方法去告訴父view不要攔截並處理點擊事件,父view應該接受這個請求直到這次點擊事件結束。io

實際的應用中,能夠在子view的ontouch事件中注入父ViewGroup的實例,並調用requestDisallowInterceptTouchEvent去阻止父view攔截點擊事件event

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;
     }
}
 request

相關文章
相關標籤/搜索