checkbox 在ListView中使用 1
大概有两种方法可以在ListView中使用CheckBox; 一种是对一个ListView里的项的数据进行处理,二是对ListView进行处理。 现在先对这两的第二种进行讨论。 ListView里面有一个方法叫作:setItemChecked这个就是将这个item设置选中或不选中的状态,如果你设置了一个监听:onItemClick然后在里面对这个赋值,且log记录,就会看到当你点击项时,这个值会是true/false间变化,但是可惜,视图却看不到变化。于是利用这个性质,加入一个CheckBox就可以了。 先定义一个ListView:
<ListView
android:id="@+id/chk_listview"
android:cacheColorHint="#00000000" android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
一个简单的布局文件,然后就是一个Adapter:
写一个继承BaseAdapter的子类:
在getView里
Item item;
if (contentView == null) {
final LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
contentView = inflater.inflate(R.layout.list_item, null);
Item = new Item();
return convertView;
然后就是list_item这个布局文件了
<com.test.CheckLinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="@+id/test_chk" android:clickable="false"
android:focusable="false" android:layout_width="wrap_content" android:layout_height="wrap_content"/>
<TextView
android:id="test"
android:layout_width="wrap_content" android:layout_height="wrap_content"/>
</com.test.CheckLinearLayout>
然后写一个自定义的
CheckLinearLayout:
extends LinearLayout implements Checkable {
public static final String TAG="CheckLinearLayout";
private CheckBox checkbox;
public CheckLinearLayout(Context context) {
super(context);
}
public CheckLinearLayout(Context context, AttributeSet set) {
super(context, set);
}
@Override
public boolean isChecked() {
return getCheckBox().isChecked();
}
@Override
public void setChecked(boolean checked) {
getCheckBox().setChecked(checked);
}
@Override
public void toggle() {
CheckBox mChecked = getCheckBox();
boolean checked=mChecked.isChecked();
setChecked(!checked);
}
private CheckBox getCheckBox() {
if (checkbox == null) {
checkbox = (CheckBox) findViewById(R.id.pancheckbox);
}
return checkbox;
}
一些准备工作都完 ,布局文件,自定义的CheckBox,剩下的就是在Activity里处理选中与取消选中状态了:
重要的是ListView需要监听:
public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) {
CheckLinearLayout chkLinearLayout = (CheckLinearLayout) view;
CheckBox mCheckBox = (CheckBox) ((LinearLayout) view).getChildAt(0);
if (!mCheckBox.isChecked()) {
if (!checkPosList.contains(new Integer(pos))) {
checkPosList.add(new Integer(pos));
}
} else {
if (checkPosList.contains(new Integer(pos))) {
checkPosList.remove(new Integer(pos));
}
}
}
checkPosList这个是一个列表,存着你选中的项的位置,不能存id,在这里id总是为0.。。。
private ArrayList<Integer> checkPosList = new ArrayList<Integer>();;需要注意的是Integer与int的区别,如果上面 checkPosList.remove((pos));会出错,它会认为你移除指定位置的项,但是如果这个列表为空时,会溢出。
这时就可以处理列表点击选中与取消选中操作了。
在下面的图checkboxlist-001.png看到效果
而选中与未选中可能太简单了,通常可能会需要处理全选与取消全选,虽然上央选中后遍历checkPosList得到选中的结果,但是不能处理全选。 这个问题下一篇blog中介绍。