用實驗方法學習View的事件傳遞機制
我寫了一個UI介面,最外層是OuterLinearLayout,內層是InnerLayout,最裡層是TargetButton,下面是實驗輸出的日誌:
2018-11-25 22:15:27.288 28703-28703/work.cloud.com.myappcloudwork D/ttt: dispatchTouchEvent in OuterLinearLayout
2018-11-25 22:15:27.289 28703-28703/work.cloud.com.myappcloudwork D/ttt: onInterceptTouchEvent in OuterLinearLayout
2018-11-25 22:15:27.290 28703-28703/work.cloud.com.myappcloudwork D/ttt: dispatchTouchEvent in InnerLayout
2018-11-25 22:15:27.290 28703-28703/work.cloud.com.myappcloudwork D/ttt: onInterceptTouchEvent in InnerLayout
2018-11-25 22:15:27.291 28703-28703/work.cloud.com.myappcloudwork D/ttt: dispatchTouchEvent in TargetButton
2018-11-25 22:15:27.292 28703-28703/work.cloud.com.myappcloudwork D/ttt: onTouchEvent in TargetButton
2018-11-25 22:15:27.294 28703-28703/work.cloud.com.myappcloudwork D/ttt: onTouchEvent in InnerLayout
2018-11-25 22:15:27.295 28703-28703/work.cloud.com.myappcloudwork D/ttt: onTouchEvent in OuterLinearLayout
從日誌可以看出,touch事件經過每一層View時,先執行dispatchTouchEvent方法,然後執行onInterceptTouchEvent,以此情形直至佈局的最裡層,我這裡是一個普通View,叫TargetButton;然後可以看出從內向外以此執行onTouchEvent方法。
如果某層做了攔截,即該層ViewGroup的onInterceptTouchEvent返回值設為true,那麼touch事件不再向下傳遞,實驗輸入日誌為:
2018-11-25 22:30:03.303 29787-29787/work.cloud.com.myappcloudwork D/ttt: dispatchTouchEvent in OuterLinearLayout
2018-11-25 22:30:03.304 29787-29787/work.cloud.com.myappcloudwork D/ttt: onInterceptTouchEvent in OuterLinearLayout
2018-11-25 22:30:03.304 29787-29787/work.cloud.com.myappcloudwork D/ttt: dispatchTouchEvent in InnerLayout
2018-11-25 22:30:03.305 29787-29787/work.cloud.com.myappcloudwork D/ttt: onInterceptTouchEvent in InnerLayout
2018-11-25 22:30:03.305 29787-29787/work.cloud.com.myappcloudwork D/ttt: onTouchEvent in InnerLayout
2018-11-25 22:30:03.306 29787-29787/work.cloud.com.myappcloudwork D/ttt: onTouchEvent in OuterLinearLayout
可以看到TargetButton的onTouchEvent的方法沒有得到執行;而攔截層以上的,以此執行onTouchEvent。
未完,待續。。。下面幾張圖不太能理解。