view過程
先自定義一個MyTextView 繼承TextView 并在dispatchTouchEvent onTouchEvent打印日志
代碼如下:
public class MyTextView extends TextView {
public MyTextView(Context context) {
super(context);
}
public MyTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
// Log.e("myTextView", "myTextView dispatchTouchEvent");
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e("myTextView", "myTextView dispatchTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.e("myTextView", "myTextView dispatchTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.e("myTextView", "myTextView dispatchTouchEvent ACTION_UP");
break;
}
return super.dispatchTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e("myTextView", "myTextView onTouchEvent ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.e("myTextView", "myTextView onTouchEvent ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.e("myTextView", "myTextView onTouchEvent ACTION_UP");
break;
}
return super.onTouchEvent(event);
}
}
最后在Activity的代碼如下:
public class MainActivity extends AppCompatActivity {
private MyTextView myTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextView = (MyTextView) findViewById(R.id.tv_show);
myTextView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.e("activity","activity onclick");
}
});
myTextView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN:
Log.e("activity","activity onTouch ACTION_DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.e("activity","activity onTouch ACTION_MOVE");
break;
case MotionEvent.ACTION_UP:
Log.e("activity","activity onTouch ACTION_UP");
break;
}
return false;
}
});
}
}
注意事項(xiàng)
注意這里的View不包含ViewGroup测砂,所以過程簡單些擅编。view是一個單獨(dú)的元素,沒有子元素因此無法向下傳遞事件妄迁,所以只能自己處理事件。
在MainActivity中满钟,我們還給MyTextView設(shè)置了OnTouchListener校翔、setOnClickListener 這個監(jiān)聽~
好了,跟View事件相關(guān)一般就這三個地方了拴鸵,一個onTouchEvent,一個dispatchTouchEvent蜗搔,一個setOnTouchListener和 setOnClickListener;
下面我們運(yùn)行劲藐,然后點(diǎn)擊按鈕,查看日志輸出:
我有意點(diǎn)擊的時候蹭了一下樟凄,不然不會觸發(fā)MOVE聘芜,手抖可能會打印一堆MOVE的日志
第一種日志輸出
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_UP
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onclick
第二種日志輸出
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_DOWN
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_MOVE
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_MOVE
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_MOVE
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_UP
25372-25372/com.lu.viewdistributionevent E/myTextView: myTextView onTouchEvent ACTION_UP
25372-25372/com.lu.viewdistributionevent E/activity: activity onclick
可以看到,不管是DOWN缝龄,MOVE汰现,UP都會按照下面的順序執(zhí)行:
- dispatchTouchEvent
- setOnTouchListener的onTouch
- onTouchEvent
- setOnClickListener的onClick
下面就跟隨日志的腳步開始源碼的探索
- 首先進(jìn)入的是dispatchTouchEvent方法
/**
* Pass the touch screen motion event down to the target view, or this
* view if it is the target.
*
* @param event The motion event to be dispatched.
* @return True if the event was handled by the view, false otherwise.
*/
public boolean dispatchTouchEvent(MotionEvent event) {
// If the event should be handled by accessibility focus first.
if (event.isTargetAccessibilityFocus()) {
// We don't have focus or no virtual descendant has it, do not handle the event.
if (!isAccessibilityFocusedViewOrHost()) {
return false;
}
// We have focus and got the event, then use normal event dispatch.
event.setTargetAccessibilityFocus(false);
}
boolean result = false;
if (mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onTouchEvent(event, 0);
}
final int actionMasked = event.getActionMasked();
if (actionMasked == MotionEvent.ACTION_DOWN) {
// Defensive cleanup for new gesture
stopNestedScroll();
}
if (onFilterTouchEventForSecurity(event)) {
if ((mViewFlags & ENABLED_MASK) == ENABLED && handleScrollBarDragging(event)) {
result = true;
}
//noinspection SimplifiableIfStatement
ListenerInfo li = mListenerInfo;// 這里面集合了所有注冊過來的listener,包括clickListener,touchListener
if (li != null && li.mOnTouchListener != null
&& (mViewFlags & ENABLED_MASK) == ENABLED// view是可點(diǎn)擊的狀態(tài)
&& li.mOnTouchListener.onTouch(this, event)) {// 執(zhí)行TouchListener.onTouch方法,并根據(jù)返回值進(jìn)行判斷
result = true;
}
if (!result && onTouchEvent(event)) {// 調(diào)用onTouchEvent,里面再執(zhí)行onClick/onLongClick
result = true;
}
}
if (!result && mInputEventConsistencyVerifier != null) {
mInputEventConsistencyVerifier.onUnhandledEvent(event, 0);
}
// Clean up after nested scrolls if this is the end of a gesture;
// also cancel it if we tried an ACTION_DOWN but we didn't want the rest
// of the gesture.
if (actionMasked == MotionEvent.ACTION_UP ||
actionMasked == MotionEvent.ACTION_CANCEL ||
(actionMasked == MotionEvent.ACTION_DOWN && !result)) {
stopNestedScroll();
}
return result;
}
OnTouchLister中的onTouch方法返回true
我有意點(diǎn)擊的時候蹭了一下叔壤,不然不會觸發(fā)MOVE瞎饲,手抖可能會打印一堆MOVE的日志
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_DOWN
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_DOWN
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_MOVE
17776-17776/com.lu.viewdistributionevent E/myTextView: myTextView dispatchTouchEvent ACTION_UP
17776-17776/com.lu.viewdistributionevent E/activity: activity onTouch ACTION_UP
從源碼可以看出,首先會先判斷有沒有設(shè)置OnTouchListener,如果OnTouchLister中的onTouch方法返回true,那么onTouchEevent就不會被調(diào)用炼绘,得出結(jié)論OnTouchListener的優(yōu)先級高于onTouchEvent嗅战。這樣做的好處就是方便外界處理點(diǎn)擊事件。同時你會發(fā)現(xiàn)setOnClickListener中的onClick也沒有被調(diào)用俺亮。為什么設(shè)置了OnTouchLister中的onTouch方法返回true驮捍,setOnClickListener中的onClick也沒有被調(diào)用呢。
- 接著再分析onTouchEvent的實(shí)現(xiàn)脚曾。
先看當(dāng)View處于不可用狀態(tài)點(diǎn)擊事件的處理過程东且。看下面代碼就知道本讥,不可用狀態(tài)的View照樣會消耗點(diǎn)擊事件珊泳,盡管看起來不可用鲁冯。
/**
* Implement this method to handle touch screen motion events.
* <p>
* If this method is used to detect click actions, it is recommended that
* the actions be performed by implementing and calling
* {@link #performClick()}. This will ensure consistent system behavior,
* including:
* <ul>
* <li>obeying click sound preferences
* <li>dispatching OnClickListener calls
* <li>handling {@link AccessibilityNodeInfo#ACTION_CLICK ACTION_CLICK} when
* accessibility features are enabled
* </ul>
*
* @param event The motion event.
* @return True if the event was handled, false otherwise.
*/
public boolean onTouchEvent(MotionEvent event) {
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
final int action = event.getAction();
//不可用狀態(tài)的View照樣會消耗點(diǎn)擊事件,盡管看起來不可用色查。
if ((viewFlags & ENABLED_MASK) == DISABLED) {
if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
return (((viewFlags & CLICKABLE) == CLICKABLE
|| (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
|| (viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE);
}
if (mTouchDelegate != null) {
if (mTouchDelegate.onTouchEvent(event)) {
return true;
}
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
(viewFlags & CONTEXT_CLICKABLE) == CONTEXT_CLICKABLE) {
switch (action) {
case MotionEvent.ACTION_UP:
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
// touch mode.
boolean focusTaken = false;
if (isFocusable() && isFocusableInTouchMode() && !isFocused()) {
focusTaken = requestFocus();
}
if (prepressed) {
// The button is being released before we actually
// showed it as pressed. Make it show the pressed
// state now (before scheduling the click) to ensure
// the user sees it.
setPressed(true, x, y);
}
if (!mHasPerformedLongPress && !mIgnoreNextUpEvent) {
// This is a tap, so remove the longpress check
removeLongPressCallback();
// Only perform take click actions if we were in the pressed state
if (!focusTaken) {
// Use a Runnable and post this rather than calling
// performClick directly. This lets other visual state
// of the view update before click actions start.
if (mPerformClick == null) {
mPerformClick = new PerformClick();
}
if (!post(mPerformClick)) {
performClick();
}
}
}
if (mUnsetPressedState == null) {
mUnsetPressedState = new UnsetPressedState();
}
if (prepressed) {
postDelayed(mUnsetPressedState,
ViewConfiguration.getPressedStateDuration());
} else if (!post(mUnsetPressedState)) {
// If the post failed, unpress right now
mUnsetPressedState.run();
}
removeTapCallback();
}
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
if (performButtonActionOnTouchDown(event)) {
break;
}
// Walk up the hierarchy to determine if we're inside a scrolling container.
boolean isInScrollingContainer = isInScrollingContainer();
// For views inside a scrolling container, delay the pressed feedback for
// a short period in case this is a scroll.
if (isInScrollingContainer) {
mPrivateFlags |= PFLAG_PREPRESSED;
if (mPendingCheckForTap == null) {
mPendingCheckForTap = new CheckForTap();
}
mPendingCheckForTap.x = event.getX();
mPendingCheckForTap.y = event.getY();
postDelayed(mPendingCheckForTap, ViewConfiguration.getTapTimeout());
} else {
// Not inside a scrolling container, so show the feedback right away
setPressed(true, x, y);
checkForLongClick(0, x, y);
}
break;
case MotionEvent.ACTION_CANCEL:
setPressed(false);
removeTapCallback();
removeLongPressCallback();
mInContextButtonPress = false;
mHasPerformedLongPress = false;
mIgnoreNextUpEvent = false;
break;
case MotionEvent.ACTION_MOVE:
drawableHotspotChanged(x, y);
// Be lenient about moving outside of buttons
if (!pointInView(x, y, mTouchSlop)) {
// Outside button
removeTapCallback();
if ((mPrivateFlags & PFLAG_PRESSED) != 0) {
// Remove any future long press/tap checks
removeLongPressCallback();
setPressed(false);
}
}
break;
}
return true;
}
return false;
}
所以得出結(jié)論:
View 的LONG_CLICKABLE屬性默認(rèn)為false晓褪,而CLICKABLE屬性是否為false和具體的view有關(guān)。準(zhǔn)確來說是可點(diǎn)擊的view其CLICKABLE為true综慎,不可點(diǎn)擊的view其CLICKABLE為false。比如Button是可點(diǎn)擊的勤庐,TextView是不可點(diǎn)擊的示惊。通過setClickable和setLongClickable,可以分別改變View的CLICKABLE和LONG_CLICKABLE的屬性愉镰。另外米罚,setOnClickListener會自動將CLICKABLE設(shè)為true,setOnLongClickListener會自動將LONG_CLICKABLE設(shè)為true.