淺談onInterceptTouchEvent、onTouchEvent與onTouch
一、onTouch
onTouch是View中OnTouchListener接口中的方法,處理View及其子類被touch是的事件處理。當(dāng)然,前提是touch時間能夠傳遞到指定的view。Q1:為什么會傳遞不到呢?
- /**
- * Interface definition for a callback to be invoked when a touch event is
- * dispatched to this view. The callback will be invoked before the touch
- * event is given to the view.
- */
- public interface OnTouchListener {
- /**
- * Called when a touch event is dispatched to a view. This allows listeners to
- * get a chance to respond before the target view.
- *
- * @param v The view the touch event has been dispatched to.
- * @param event The MotionEvent object containing full information about
- * the event.
- * @return True if the listener has consumed the event, false otherwise.
- */
- boolean onTouch(View v, MotionEvent event);
- }
二、onTouchEvent
onTouchEvent同樣也是在view中定義的一個方法。處理傳遞到view 的手勢事件。手勢事件類型包括ACTION_DOWN,ACTION_MOVE,ACTION_UP,ACTION_CANCEL四種事件。
- /**
- * Implement this method to handle touch screen motion events.
- *
- * @param event The motion event.
- * @return True if the event was handled, false otherwise.
- */
- public boolean onTouchEvent(MotionEvent event) {
- ……
- ……
- }
一旦onTouchEvent方法被調(diào)用,并返回true則這個手勢事件就結(jié)束了,并不會向下傳遞到子控件。Q2:onTouchEvent什么時候被調(diào)用呢?
三、onInterceptTouchEvent
onInterceptTouchEvent是在ViewGroup里面定義的。Android中的layout布局類一般都是繼承此類的。onInterceptTouchEvent是用于攔截手勢事件的,每個手勢事件都會先調(diào)用onInterceptTouchEvent。
- public boolean onInterceptTouchEvent(MotionEvent ev) {
- return false;
- }
此方法返回false,則手勢事件會向子控件傳遞;返回true,則調(diào)用onTouchEvent方法。
原文鏈接:http://www.cnblogs.com/halzhang/archive/2010/08/18/1802611.html
【編輯推薦】