Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

ListView 的 setOnItemClickListener 為什麼沒反應?從事件分發機制找答案

編輯:關於 Android 開發

ListView 的 setOnItemClickListener 為什麼沒反應?從事件分發機制找答案

問題現場

做專案時遇到一個狀況:ListView 設了 setOnItemClickListener,卻完全沒有回呼 onItemClick()。我的 item 版面裡有一顆 Button。

網路上找到的解法有兩種:

  1. 在 item 內的 Button、CheckBox 等控件上加 android:focusable="false"、android:clickable="false"、android:focusableInTouchMode="false"。
  2. 在 item 最外層加上 android:descendantFocusability="blocksDescendants"。

多數文章的說法是:當 ListView 的 item 裡含有 Button、CheckBox 這類控件時,Android 會預設把焦點給這些子控件,導致 item 本身拿不到焦點,onItemClick 因此不會觸發。

這個解釋聽起來合理,但我想驗證它到底對不對,於是有了這篇。要談清楚,得先從事件分發講起。

事件分發的三個關鍵方法

dispatchTouchEvent(MotionEvent ev) — 負責事件分發。事件傳到某個 View 時呼叫,回傳值受自身的 onTouchEvent() 與子 View 的 dispatchTouchEvent() 影響。

onInterceptTouchEvent(MotionEvent ev) — 在上一個方法中呼叫,回傳值表示是否攔截事件,預設 false(不攔截)。

onTouchEvent(MotionEvent event) — 在 dispatchTouchEvent 中呼叫,負責處理點擊事件,回傳值表示是否消耗該事件。

點擊發生後的流程大致如上圖所示。

既然預設不攔截,那 item 的點擊應該會走到 ListView 的 onTouchEvent()。但我翻 ListView 原始碼,發現它根本沒有這個方法。往父類 AbsListView 找——還真有。

@Override
public boolean onTouchEvent(MotionEvent ev) {
    if (!isEnabled()) {
        return isClickable() || isLongClickable();
    }
    // ... 前置處理與 FastScroll 判斷省略
    switch (ev.getActionMasked()) {
        case MotionEvent.ACTION_DOWN:
            onTouchDown(ev); break;
        case MotionEvent.ACTION_MOVE:
            onTouchMove(ev, vtev); break;
        case MotionEvent.ACTION_UP:
            onTouchUp(ev); break;          // ← 重點在這裡
        // ... 其餘分支省略
    }
    return true;
}

onItemClick 是在手指離開螢幕的那一刻觸發的,所以問題一定出在 ACTION_UP 分支呼叫的 onTouchUp()。

onTouchUp 裡的那個 if 判斷

private void onTouchUp(MotionEvent ev) {
    switch (mTouchMode) {
        case TOUCH_MODE_DOWN:
        case TOUCH_MODE_TAP:
        case TOUCH_MODE_DONE_WAITING:
            final int motionPosition = mMotionPosition;
            final View child = getChildAt(motionPosition - mFirstPosition);
            if (child != null) {
                if (mTouchMode != TOUCH_MODE_DOWN) {
                    child.setPressed(false);
                }
                final float x = ev.getX();
                final boolean inList = x > mListPadding.left && x < getWidth() - mListPadding.right;
                if (inList && !child.hasFocusable()) {   // ← 關鍵條件
                    if (mPerformClick == null) {
                        mPerformClick = new PerformClick();
                    }
                    // ... 後續處理並最終呼叫 performClick.run()
                }
            }
            mTouchMode = TOUCH_MODE_REST;
            updateSelectorState();
            break;
    }
}

拿到 item 的 View 之後,第 15 行做了一個判斷:!child.hasFocusable()。也就是說,只有當 item 的 hasFocusable() 回傳 false 時,後面的點擊邏輯才會執行。這就是問題的關鍵。

往下追 PerformClick:

private class PerformClick extends WindowRunnnable implements Runnable {
    int mClickMotionPosition;

    @Override
    public void run() {
        if (mDataChanged) return;
        final ListAdapter adapter = mAdapter;
        final int motionPosition = mClickMotionPosition;
        if (adapter != null && mItemCount > 0
                && motionPosition != INVALID_POSITION
                && motionPosition < adapter.getCount()
                && sameWindow()) {
            final View view = getChildAt(motionPosition - mFirstPosition);
            if (view != null) {
                performItemClick(view, motionPosition, adapter.getItemId(motionPosition));
            }
        }
    }
}

AbsListView 的 performItemClick() 主要處理 CHOICE_MODE 的多選/單選狀態,最後把發派權交回父類:

@Override
public boolean performItemClick(View view, int position, long id) {
    boolean handled = false;
    boolean dispatchItemClick = true;
    // ... CHOICE_MODE 相關處理省略
    if (dispatchItemClick) {
        handled |= super.performItemClick(view, position, id);
    }
    return handled;
}

而 View 的實作就是我們熟悉的那段:

public boolean performItemClick(View view, int position, long id) {
    final boolean result;
    if (mOnItemClickListener != null) {
        playSoundEffect(SoundEffectConstants.CLICK);
        mOnItemClickListener.onItemClick(this, view, position, id);
        result = true;
    } else {
        result = false;
    }
    if (view != null) {
        view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED);
    }
    return result;
}

終點找到了。整條鏈路能不能走通,完全取決於 !child.hasFocusable() 這個條件是否成立。

hasFocusable() 到底在看什麼

ViewGroup 的實作會遍歷所有子 View,只要有任何一個子 View 回傳 true,它自己就回傳 true:

@Override
public boolean hasFocusable() {
    if ((mViewFlags & VISIBILITY_MASK) != VISIBLE) {
        return false;
    }
    if (isFocusable()) {
        return true;
    }
    final int descendantFocusability = getDescendantFocusability();
    if (descendantFocusability != FOCUS_BLOCK_DESCENDANTS) {
        final int count = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < count; i++) {
            if (children[i].hasFocusable()) {
                return true;
            }
        }
    }
    return false;
}

而 View 本身的實作相對簡單:

public boolean hasFocusable() {
    if (!isFocusableInTouchMode()) {
        for (ViewParent p = mParent; p instanceof ViewGroup; p = p.getParent()) {
            if (((ViewGroup) p).shouldBlockFocusForTouchscreen()) {
                return false;
            }
        }
    }
    return (mViewFlags & VISIBILITY_MASK) == VISIBLE && isFocusable();
}

回頭驗證兩個解法

情況一:不加 descendantFocusability

ViewGroup 會遍歷所有子 View。把 Button 的 focusable 設為 false 之後,所有子 View 都不搶焦點,item 本身的 hasFocusable() 也就回傳 false,if 條件成立,回呼執行。

情況二:加上 descendantFocusability="blocksDescendants"

ViewGroup 直接跳過遍歷(因為 descendantFocusability == FOCUS_BLOCK_DESCENDANTS),自己若不是 focusable 就回傳 false,同樣讓 if 成立。

兩種做法殊途同歸,本質都是讓 item 的 hasFocusable() 回傳 false。網路上流傳的說法方向是對的,只是知其然更要知其所以然——真正的閘門不在「焦點」這個模糊概念,而在 onTouchUp() 裡那個具體的條件判斷。

實務建議:如果 item 內部的 Button 本身也需要點擊,兩種解法都會讓它失效,這時更合適的做法是在 Button 的 onClick 裡自行往上取 position 處理,或改用 RecyclerView 搭配更清晰的點擊分派設計。

如果這篇對你有幫助,歡迎按讚或留言。若有任何錯誤也請不吝指正。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved