Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android/OPhone 開發:讓 ListView 中的 Button 與 onItemClick 和平共處

編輯:Android 開發實例

在 ListView 的列表項裡塞入可點擊的子控制項(Button、CheckBox 這類),是新手最容易踩到的坑:一旦 row 裡出現了 Button,整行的 onItemClick 就再也觸發不了。原因其實很單純——Button 預設是 focusable 的,會把焦點與觸摸事件整包吃掉,事件自然冒不到 ListView 這層。

解法:把子控制項的 focusable 關掉

只要在这些具有点击能力的子控制项上明确加上 android:focusable="false",事件传递就会恢复正常。下面这份布局同时做到了两件事:点击非 CheckBox、非 Button 的空白区域时会触发 onItemClick;点击 Button 本身时则由它自己的 onClick 接手。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_height="fill_parent"
    android:id="@+id/LinearLayoutGameListItem"
    android:layout_width="fill_parent"
    android:gravity="center_vertical"
    android:layout_marginLeft="@dimen/mygamecenter_common_margin"
    android:layout_marginRight="@dimen/mygamecenter_common_margin">

    <CheckBox android:id="@+id/CheckBoxGameListItem"
        android:focusable="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"></CheckBox>

    <Button android:text="@string/top" android:id="@+id/ButtonTop"
        android:textColor="#FFFFFF"
        android:focusable="false"
        android:layout_width="wrap_content"
        android:layout_height="@dimen/game_list_item_button_height"
        android:layout_marginRight="@dimen/game_list_item_button_margin_right"
        android:paddingLeft="@dimen/game_list_item_button_padding_left"
        android:paddingRight="@dimen/game_list_item_button_padding_right"
        android:background="@drawable/button_cool_small_selector"></Button>
</LinearLayout>

幾點實務補充

  • 除了 focusable,有些情境還要一併把 android:focusableInTouchMode 設為 false,或改用 android:descendantFocusability="blocksDescendants" 從父容器層面阻斷子控制項搶焦點。
  • 如果列表項裡的可點擊元件很多,比較乾淨的做法是在 Adapter 的 getView() 中直接呼叫 button.setFocusable(false),避免每個 layout 都重複宣告。
  • 事件要在哪裡處理,取決於互動設計:整列點擊交給 OnItemClickListener,按鈕動作則在 getView() 裡綁定 OnClickListener,兩者並不衝突。

這個設定看起來只是少少一行屬性,卻是 ListView 互動設計的分水嶺。網路上仍有不少人卡在同一步,因此特別整理出來分享。

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