View中的onTouchEvent()與setOnTouchListener()中的ontouch()方法的事件處理先后順序


Touch事件的兩種情況
1.覆寫View.class中定義的onTouchEvent-->基於事件回調監聽方式

@Override
public boolean onTouchEvent(MotionEvent ev) {
// TODO
return super.onTouchEvent(ev);
}

 


2.通過監聽的形式,監聽View.class中的setOnTouchListener(listener)--->基於監聽器事件監聽方式

/**
* Register a callback to be invoked when a touch event is sent to this view.
* @param l the touch listener to attach to this view
*/
public void setOnTouchListener(OnTouchListener l) {
getListenerInfo().mOnTouchListener = l;
}

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

3.兩個方法的調用順序是怎樣
經過debug測試,基於監聽器的優先於基於回調的,源碼上分析也一樣.
4.基於監聽器的返回值值是否影響基於回調的

父類方法中會先判斷接口回調的是不是返回true,是的話就不執行ontouch方法
會影響,如果return true,基於回調onTouch就不執行

5.舉個栗子:
在一個Activity里面放一個TextView的實例tv,並且這個tv的屬性設定為 fill_parent
在這種情況下,當手放到屏幕上的時候,首先會是tv響應touch事件,執行onTouch方法。

如果onTouch返回值為true,
表示這個touch事件被onTouch方法處理完畢,不會把touch事件再傳遞給Activity,
也就是說onTouchEvent方法不會被調用。
(當把手放到屏幕上后,onTouch方法被一遍一遍地被調用)

如果onTouch的返回值是false,
表示這個touch事件沒有被tv完全處理,onTouch返回以后,touch事件被傳遞給Activity,
onTouchEvent方法被調用。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2026 CODEPRJ.COM