本文整理並完美解決在 Android 中使用 ListView 進行 CheckBox 批量操作時遇到的各類問題。
使用 ListActivity 可以很方便地綁定一組資料或一個查詢,但實作過程中往往會踩到一些坑。以下把常見問題與解法記錄下來,既是備忘,也希望幫其他開發者少走彎路。
Item 數量可用 getCount 取得。經實測,其回傳值等於畫面上顯示的 Item 數,這個數字可能小於實際綁定的資料筆數。
那麼若有額外、非綁定資料源的資料需要編輯保存時該怎麼辦?解法是:自訂 ListAdapter,把額外需要保存的資料存進 Adapter 中。
在 item 裡加入 CheckBox 時容易出問題,常見現象有:
(1) ListView 無法響應點擊事件;
(2) 點擊第一個 Item 時,最後一個 Item 也會觸發點擊(反之亦然)。
以上兩個都是我實際遇到的 bug。反覆測試後發現,根本原因在於 CheckBox 搶佔焦點與點擊事件的優先級高於 ListView。對應解法如下:
(1) 將 CheckBox 的 focusable 設為 false;
(2) 再將 CheckBox 的 clickable 設為 false。
以下為程式片段,僅供參考:
<!-- ans_list.xml -->
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingLeft="8dp"
android:paddingRight="8dp">
<TextView
android:id="@+id/ans_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:gravity="center"
android:textSize="15sp"
android:textStyle="bold" />
<RelativeLayout
android:id="@+id/ans_foot"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:paddingLeft="8sp"
android:paddingRight="8sp">
<CheckBox
android:id="@+id/ans_cbx_select"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginLeft="10sp"
android:checked="false" />
<Button
android:id="@+id/ans_btn_showInMap"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ans_cbx_select"
android:text="@string/ans_btn_showInMap" />
</RelativeLayout>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="@id/ans_foot"
android:layout_below="@id/ans_title"
android:drawSelectorOnTop="false">
</ListView>
<TextView
android:id="@android:id/empty"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:text="@string/ans_list_empty"
android:textSize="25sp"
android:textStyle="bold">
</TextView>
</RelativeLayout>