1、onTouch()方法:
onTouch方式是View的OnTouchListener接口中定義的方法。
當一個View綁定了OnTouchListener后,當有Touch事件觸發時,就會調用onTouch方法。
(當把手放到View上后,onTouch方法被一遍一遍的調用)
2、onTouchEvent()方法:
onTouchEvent方法時重載的Activity的方法
重寫了Acitivity的onTouchEvent方法后,當屏幕有Touch事件時,此方法就會被調用。
(當把手放到Activity上時,onTouchEvent方法會一遍一遍的被調用)
3、Touch事件的傳遞:
在一個Activity里面放一個TextView的實例tv,並且這個tv的屬性設定為march_parent
在這種情況下,當手放到屏幕上的時候,首先會是tv響應Touch事件,執行onTouch方法。
如果onTouch返回值為true,表示這個Touch事件被onTouch方法處理完畢,不會把Touch事件再傳遞給Activity
也就是說onTouchEvent方法不會被調用
(手放到屏幕上后,onTouch方法會被一遍一遍的調用)
如果onTouch返回值為false,表示這個Touch事件沒有被tv完全處理,onTouch返回以后,Touch事件被傳遞給Activity,
onTouchEvent方法調用
(當把手放到屏幕上后,onTouch方法調用一次后,onTouchEvent方法被一遍一遍的調用)
測試:
1、MyLinearLayout繼承LinearLayout,並重寫onTouchEvent方法
1 import android.content.Context; 2 import android.util.AttributeSet; 3 import android.util.Log; 4 import android.view.MotionEvent; 5 import android.widget.LinearLayout; 6 7 public class MyLinearLayout extends LinearLayout{ 8 9 public MyLinearLayout(Context context, AttributeSet attrs) { 10 super(context, attrs); 11 } 12 13 @Override 14 public boolean onTouchEvent(MotionEvent event) { 15 switch (event.getAction()) { 16 case MotionEvent.ACTION_DOWN://0 17 Log.e("TAG", "LinearLayout onTouchEvent 按住"); 18 break; 19 case MotionEvent.ACTION_UP://1 20 Log.e("TAG", "LinearLayout onTouchEvent onTouch抬起"); 21 break; 22 case MotionEvent.ACTION_MOVE://2 23 Log.e("TAG", "LinearLayout onTouchEvent 移動"); 24 break; 25 } 26 return super.onTouchEvent(event); 27 } 28 29 @Override 30 public boolean dispatchTouchEvent(MotionEvent ev) { 31 return super.dispatchTouchEvent(ev); 32 } 33 34 @Override 35 public void setOnTouchListener(OnTouchListener l) { 36 super.setOnTouchListener(l); 37 } 38 39 }
2、在MainActivity中聲明MyLinearLayout,並設置觸摸監聽和點擊監聽,同時MainActivity自己也有onTouchEvent方法,重寫看結果
1 import android.app.Activity; 2 import android.os.Bundle; 3 import android.util.Log; 4 import android.view.MotionEvent; 5 import android.view.View; 6 import android.view.View.OnClickListener; 7 import android.view.View.OnTouchListener; 8 9 public class MainActivity extends Activity { 10 11 MyLinearLayout ll; 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 17 ll = (MyLinearLayout) findViewById(R.id.ll); 18 //觸摸監聽 19 ll.setOnTouchListener(new OnTouchListener() { 20 21 @Override 22 public boolean onTouch(View v, MotionEvent event) { 23 //Log.e("TAG", event.getX()+" "+event.getY()); 24 25 switch (event.getAction()) { 26 case MotionEvent.ACTION_DOWN://0 27 Log.e("TAG", "LinearLayout onTouch按住"); 28 break; 29 case MotionEvent.ACTION_UP://1 30 Log.e("TAG", "LinearLayout onTouch抬起"); 31 break; 32 case MotionEvent.ACTION_MOVE://2 33 Log.e("TAG", "LinearLayout onTouch移動"); 34 break; 35 } 36 //事件分發 37 //1、setOnTouchListener單獨使用的時候返回值需要true,這樣才能保證移動的時候獲取相應的監聽,而非一次監聽(即只有按下事件) 38 //返回false,表示沒有被處理,將向父View傳遞。只能監聽到view的"按下"事件,"移動"和"抬起"都不能監聽到。因為down事件未結束 39 //返回true,消耗此事件,表示正確接收並處理,不在分發。"按下""抬起""移動"都能監聽到了 40 41 //2、setOnTouchListener和setOnClickListener同時使用時, 42 //返回true,事件被onTouch消耗掉了,因而不會在繼續向下傳遞。只能監聽"按下""抬起""移動",不能監聽到"點擊"; 43 //返回false,"按下""抬起""移動""點擊"都能監聽 44 45 return false; 46 /** 47 * onTouch是優先於onClick的,並且執行了兩次,一次是ACTION_DOWN,一次是ACTION_UP(可能還會有多次ACTION_MOVE), 48 * 因此事件傳遞的順序是先經過OnTouch,再傳遞給onClick 49 * 50 */ 51 } 52 }); 53 54 ll.setOnClickListener(new OnClickListener() { 55 @Override 56 public void onClick(View v) { 57 Log.e("TAG", "onClick點擊事件"); 58 } 59 }); 60 } 61 62 //事件分發:public boolean dispatchTouchEvent(MotionEvent ev) 63 //當監聽到事件時,首先由Activity的捕獲到,進入事件分發處理流程,無論是Activity還是View,事件分發自身也具有消費能力 64 //如果事件分發返回true,表示該事件在本層不再進行分發且已經已經在事件分發自身中被消費了。 65 //如果你不想Activity中的任何控件具有任何的事件消費能力,可以直接重寫Activity的dispatchTouchEvent方法,返回true就可以了 66 @Override 67 public boolean dispatchTouchEvent(MotionEvent ev) { 68 // TODO Auto-generated method stub 69 return super.dispatchTouchEvent(ev); 70 } 71 72 73 @Override 74 public boolean onTouchEvent(MotionEvent event) { 75 switch (event.getAction()) { 76 case MotionEvent.ACTION_DOWN://0 77 Log.e("TAG", "Activity onTouchEvent按住"); 78 break; 79 case MotionEvent.ACTION_UP://1 80 Log.e("TAG", "Activity onTouchEvent抬起"); 81 break; 82 case MotionEvent.ACTION_MOVE://2 83 Log.e("TAG", "Activity onTouchEvent移動"); 84 break; 85 } 86 return super.onTouchEvent(event); 87 } 88 89 90 }
3、由於MyLinearLayout繼承了LinearLayou,但是XML並不認識他,所以在xml中搭建布局的時候,一定要包名帶類名
1 <com.example.lesson6_ontouch.MyLinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:id="@+id/ll" 3 android:layout_width="match_parent" 4 android:layout_height="match_parent"> 5 6 <TextView 7 android:id="@+id/tv" 8 android:layout_width="match_parent" 9 android:layout_height="match_parent" 10 android:text="hsss"/> 11 12 </com.example.lesson6_ontouch.MyLinearLayout>
測試結果:
4、下面貼一位博主的分析 Android事件分發機制完全解析,帶你從源碼的角度徹底理解(上)
首先你需要知道一點,只要你觸摸到了任何一個控件,就一定會調用該控件的dispatchTouchEvent方法。那當我們去點擊按鈕的時候,就會去調用Button類里的dispatchTouchEvent方法,可是你會發現Button類里並沒有這個方法,那么就到它的父類TextView里去找一找,你會發現TextView里也沒有這個方法,那沒辦法了,只好繼續在TextView的父類View里找一找,這個時候你終於在View里找到了這個方法,示意圖如下:
然后我們來看一下View中dispatchTouchEvent方法的源碼:
1 public boolean dispatchTouchEvent(MotionEvent event) { 2 if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED && 3 mOnTouchListener.onTouch(this, event)) { 4 return true; 5 } 6 return onTouchEvent(event); 7 }
我們可以看到,在這個方法內,首先是進行了一個判斷,如果mOnTouchListener != null,(mViewFlags & ENABLED_MASK) == ENABLED和mOnTouchListener.onTouch(this, event)這三個條件都為真,就返回true,否則就去執行onTouchEvent(event)方法並返回。
先看一下第一個條件,mOnTouchListener這個變量是在哪里賦值的呢?我們尋找之后在View里發現了如下方法:
1
2
3
|
public
void
setOnTouchListener(OnTouchListener l) {
mOnTouchListener = l;
}
|
mOnTouchListener正是在setOnTouchListener方法里賦值的,也就是說只要我們給控件注冊了touch事件,mOnTouchListener就一定被賦值了。
第二個條件(mViewFlags & ENABLED_MASK) == ENABLED是判斷當前點擊的控件是否是enable的,按鈕默認都是enable的,因此這個條件恆定為true。
第三個條件就比較關鍵了,mOnTouchListener.onTouch(this, event),其實也就是去回調控件注冊touch事件時的onTouch方法。也就是說如果我們在onTouch方法里返回true,就會讓這三個條件全部成立,從而整個方法直接返回true。如果我們在onTouch方法里返回false,就會再去執行onTouchEvent(event)方法。
現在我們可以結合前面的例子來分析一下了,首先在dispatchTouchEvent中最先執行的就是onTouch方法,因此onTouch肯定是要優先於onClick執行的,也是印證了剛剛的打印結果。而如果在onTouch方法里返回了true,就會讓dispatchTouchEvent方法直接返回true,不會再繼續往下執行。而打印結果也證實了如果onTouch返回true,onClick就不會再執行了。
根據以上源碼的分析,從原理上解釋了我們前面例子的運行結果。而上面的分析還透漏出了一個重要的信息,那就是onClick的調用肯定是在onTouchEvent(event)方法中的!那我們馬上來看下onTouchEvent的源碼,如下所示:
1 public boolean onTouchEvent(MotionEvent event) { 2 final float x = event.getX(); 3 final float y = event.getY(); 4 final int viewFlags = mViewFlags; 5 final int action = event.getAction(); 6 7 if ((viewFlags & ENABLED_MASK) == DISABLED) { 8 if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) { 9 setPressed(false); 10 } 11 // A disabled view that is clickable still consumes the touch 12 // events, it just doesn't respond to them. 13 return (((viewFlags & CLICKABLE) == CLICKABLE 14 || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) 15 || (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE); 16 } 17 if (mTouchDelegate != null) { 18 if (mTouchDelegate.onTouchEvent(event)) { 19 return true; 20 } 21 } 22 23 if (((viewFlags & CLICKABLE) == CLICKABLE || 24 (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) || 25 (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) { 26 switch (action) { 27 case MotionEvent.ACTION_UP: 28 boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0; 29 if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) { 30 // take focus if we don't have it already and we should in 31 // touch mode. 32 boolean focusTaken = false; 33 if (isFocusable() && isFocusableInTouchMode() && !isFocused()) { 34 focusTaken = requestFocus(); 35 } 36 37 if (prepressed) { 38 // The button is being released before we actually 39 // showed it as pressed. Make it show the pressed 40 // state now (before scheduling the click) to ensure 41 // the user sees it. 42 setPressed(true, x, y); 43 } 44 45 if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) { 46 // This is a tap, so remove the longpress check 47 removeLongPressCallback(); 48 49 // Only perform take click actions if we were in the pressed state 50 if (!focusTaken) { 51 // Use a Runnable and post this rather than calling 52 // performClick directly. This lets other visual state 53 // of the view update before click actions start. 54 if (mPerformClick == null) { 55 mPerformClick = new PerformClick(); 56 } 57 if (!post(mPerformClick)) { 58 performClick(); 59 } 60 } 61 } 62 63 if (mUnsetPressedState == null) { 64 mUnsetPressedState = new UnsetPressedState(); 65 } 66 67 if (prepressed) { 68 postDelayed(mUnsetPressedState, 69 ViewConfiguration.getPressedStateDuration()); 70 } else if (!post(mUnsetPressedState)) { 71 // If the post failed, unpress right now 72 mUnsetPressedState.run(); 73 } 74 75 removeTapCallback(); 76 } 77 mIgnoreNextUpEvent = false; 78 break; 79 80 case MotionEvent.ACTION_DOWN: 81 mHasPerformedLongPress = false; 82 83 if (performButtonActionOnTouchDown(event)) { 84 break; 85 } 86 87 // Walk up the hierarchy to determine if we're inside a scrolling container. 88 boolean isInScrollingContainer = isInScrollingContainer(); 89 90 // For views inside a scrolling container, delay the pressed feedback for 91 // a short period in case this is a scroll. 92 if (isInScrollingContainer) { 93 mPrivateFlags |= PFLAG_PREPRESSED; 94 if (mPendingCheckForTap == null) { 95 mPendingCheckForTap = new CheckForTap(); 96 }