首页 / 操作系统 / Linux / Android功能模块化之ListView中CheckBox批量操作
ListView加载CheckBox,在进行全选操作时,或全选状态下,勾选ListView中Item的CheckBox时,全选状态没有改变之类的情况。ListView中itemCheckBox与全选AllCheckBox存在以下关联:(1)AllCheckBox选中状态与未选中状态下,itemCheckBox随之变化;(2)itemCheckBox未选中时,应AllCheckBox为未选中状态;(3)itemCheckBox选中时,需判断ListView中所有的checkbox是否处于选中状态,若为选中状态,则将AllCheckBox状态改为选中,否则为未选中状态。解决思路:(1)在Adapter存下每个checkBox的状态;(2)通过AllCheckBox状态改变itemCheckBox状态;(3)通过判断Adapter中所有checkbox的选中状态,去更新AllCheckBox状态;(4)使用Handler更新AllCheckBox状态。实现代码:1)定义ListView的item.xml<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:Android="http://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>2)定义ListView的Adapter,以下为一些关键的源代码2.1)定义变量private HashMap<Integer, Boolean> isSelected = null;//存储checkbox状态private Handler statusHandler = null;//更新AllCheckBox的handlerprivate class ViewHolder {TextView tvTime, tvPlace, tvMoney;CheckBox cbSelect;}2.2)定义判断全选状态的方法 private boolean isAllSelected() {
for (int i = 0; i < isSelected.size(); i++) {
if (!isSelected.get(i)) {
return false;
}
}
return true;
}2.3)定义选择checkBox方法public void select(int potision, boolean isChecked) {
isSelected.put(potision, isChecked);//记录下当前checkBox的状态
Message msg = statusHandler.obtainMessage();
if (isChecked) {
if (isAllSelected()) {
msg.what = MainActivity.ALL_SELECTED_CHECK;//将AllCheckbox状态改为选中
} else {
msg.what = MainActivity.NOT_ALL_SELECTED_CHECK;//将AllCheckBox改成未选中
}
} else {
msg.what = MainActivity.NOT_ALL_SELECTED_CHECK;//将AllCheckBox改成未选中
}
statusHandler.sendMessage(msg);
}