view點(diǎn)擊事件處理過程

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í)行:

  1. dispatchTouchEvent
  2. setOnTouchListener的onTouch
  3. onTouchEvent
  4. 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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市丈探,隨后出現(xiàn)的幾起案子录择,更是在濱河造成了極大的恐慌,老刑警劉巖碗降,帶你破解...
    沈念sama閱讀 223,002評論 6 519
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件隘竭,死亡現(xiàn)場離奇詭異,居然都是意外死亡讼渊,警方通過查閱死者的電腦和手機(jī)动看,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,357評論 3 400
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來爪幻,“玉大人菱皆,你說我怎么就攤上這事“じ澹” “怎么了仇轻?”我有些...
    開封第一講書人閱讀 169,787評論 0 365
  • 文/不壞的土叔 我叫張陵,是天一觀的道長奶甘。 經(jīng)常有香客問我篷店,道長,這世上最難降的妖魔是什么甩十? 我笑而不...
    開封第一講書人閱讀 60,237評論 1 300
  • 正文 為了忘掉前任船庇,我火速辦了婚禮,結(jié)果婚禮上侣监,老公的妹妹穿的比我還像新娘鸭轮。我一直安慰自己,他們只是感情好橄霉,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,237評論 6 398
  • 文/花漫 我一把揭開白布窃爷。 她就那樣靜靜地躺著邑蒋,像睡著了一般。 火紅的嫁衣襯著肌膚如雪按厘。 梳的紋絲不亂的頭發(fā)上医吊,一...
    開封第一講書人閱讀 52,821評論 1 314
  • 那天,我揣著相機(jī)與錄音逮京,去河邊找鬼卿堂。 笑死,一個胖子當(dāng)著我的面吹牛懒棉,可吹牛的內(nèi)容都是我干的草描。 我是一名探鬼主播,決...
    沈念sama閱讀 41,236評論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼策严,長吁一口氣:“原來是場噩夢啊……” “哼穗慕!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起妻导,我...
    開封第一講書人閱讀 40,196評論 0 277
  • 序言:老撾萬榮一對情侶失蹤逛绵,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后倔韭,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體术浪,經(jīng)...
    沈念sama閱讀 46,716評論 1 320
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,794評論 3 343
  • 正文 我和宋清朗相戀三年寿酌,在試婚紗的時候發(fā)現(xiàn)自己被綠了添吗。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,928評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡份名,死狀恐怖碟联,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情僵腺,我是刑警寧澤鲤孵,帶...
    沈念sama閱讀 36,583評論 5 351
  • 正文 年R本政府宣布,位于F島的核電站辰如,受9級特大地震影響普监,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜琉兜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,264評論 3 336
  • 文/蒙蒙 一凯正、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧豌蟋,春花似錦廊散、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,755評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽运准。三九已至,卻和暖如春缭受,著一層夾襖步出監(jiān)牢的瞬間胁澳,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,869評論 1 274
  • 我被黑心中介騙來泰國打工米者, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留韭畸,地道東北人。 一個月前我還...
    沈念sama閱讀 49,378評論 3 379
  • 正文 我出身青樓蔓搞,卻偏偏與公主長得像陆盘,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子败明,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,937評論 2 361

推薦閱讀更多精彩內(nèi)容