在 ListView 裡放 CheckBox 做多選,最常見的 bug 是:勾選某個 item 後,頂部的全選框狀態沒有跟著更新;或者全選之后再取消一項,全選框卻仍亮著。要把這套邏輯寫對,先把三條規則定清楚。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/background_color"
android:orientation="horizontal"
android:paddingBottom="10dip"
android:paddingTop="10dip">
<TextView
android:id="@+id/tv_time"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="時間"
android:textColor="@color/black"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_place"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.5"
android:gravity="center"
android:text="地點"
android:textColor="@color/black"
android:textSize="15sp" />
<TextView
android:id="@+id/tv_money"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1.0"
android:gravity="center"
android:text="金額"
android:textColor="@color/black"
android:textSize="15sp" />
<CheckBox
android:id="@+id/cb_select"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_weight="0.5"
android:button="@drawable/cb_item_selected"
android:focusable="false"
android:focusableInTouchMode="false" />
</LinearLayout>
先宣告狀態容器與 Handler:
private HashMap<Integer, Boolean> isSelected = null; // 存放 checkbox 狀態
private Handler statusHandler = null; // 更新 AllCheckBox 用
private class ViewHolder {
TextView tvTime, tvPlace, tvMoney;
CheckBox cbSelect;
}
再寫一個判斷是否全選的方法:
private boolean isAllSelected() {
for (int i = 0; i < isSelected.size(); i++) {
if (!isSelected.get(i)) {
return false;
}
}
return true;
}
最後是切換單一 CheckBox 並同步全選框:
public void select(int position, boolean isChecked) {
isSelected.put(position, isChecked); // 記錄當前 checkbox 狀態
Message msg = statusHandler.obtainMessage();
if (isChecked) {
if (isAllSelected()) {
msg.what = MainActivity.ALL_SELECTED_CHECK; // 全選框改為選中
} else {
msg.what = MainActivity.NOT_ALL_SELECTED_CHECK; // 全選框改為未選中
}
} else {
msg.what = MainActivity.NOT_ALL_SELECTED_CHECK;
}
statusHandler.sendMessage(msg);
}
需要提醒的是,Adapter 的 getView 會被反覆重用,因此每次綁定資料時都要依 isSelected 的值重新設定 CheckBox 的勾選狀態,否則捲動後就會出現狀態錯位。