checkbox 在ListView中使用 2
关于全选的问题,因为第一篇文章已经讨论了选中与取消的实现,现在介绍全选的实现。 同样是第二种实现方法: ListView有一个setItemChecked方法,现在这个方法用得上了。
你的数据列表是:private List mList = new ArrayList();
完成的布局文件是:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content">
<Button
android:id="@+id/check_all" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="check all"
android:layout_weight="1"/>
<Button
android:id="@+id/un_check_all" android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="uncheck all"
android:layout_weight="1"/>
<ListView
android:id="@+id/"
android:cacheColorHint="#00000000" android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
加了两个按钮,进行全选与了取消全选。
checkAllBtn = (Button) findViewById(R.id.check_all);
unCheckAllBtn = (Button) findViewById(R.id.un_check_all);
checkAllBtn.setOnClickListener(clickListener);
unCheckAllBtn.setOnClickListener(clickListener);
public void onClick(View view) {
switch (view.getId()) {
case R.id.check_all:
checkAll();
break;
case R.id.un_check_all:
unCheckAll();
break;
default:
break;
}
}
private ListView mListView;
//全选:
private void checkAll() {
for (int i = 0; i < mList.size(); i++) {
if (!checkPosList.contains(new Integer(i))) {这里对已经添加选中状态的就不处理了,
checkPosList.add(new Integer(i)); 需要添加的是Object不能是int。
mListView.setItemChecked(i, true);利用了ListView的这个方法,就可以让你的ListView出现选中状态了,如果这句删除了,虽然checkPosList包含了所有的选中项,视图中却看不到,可以试试看效果。
}
}
contactListAdapter.notifyDataSetChanged();
}
取消全选:
private void unCheckAll() {
for (int i = 0; i < mList.size(); i++) {
mListView.setItemChecked(i, false);将所有的选中状态取消。
}
checkPosList.clear();
contactListAdapter.notifyDataSetChanged();
}
到此,结束。图片效果: