1、单击listview的item时取得相应position的checkbox:
listView.setOnItemClickListener(itemListener);
OnItemClickListener itemListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
messageBoxAdapter.itemSeleted(arg1<span style="font-family: Arial, Helvetica, sans-serif;">);//调用adapter的方法来设置checkbox的勾选状态</span>
}
};
参数含义:arg0=整个listview布局,arg1=当前点击item布局,arg2=当前点击项索引,arg3=id
MessageBoxAdapter的相应代码:
public void itemSelected(View arg1) {
ViewHolder viewHolder = (ViewHolder) arg1.getTag();//通过tag取得ViewHolder对象,这样就省去了通过层层的findViewById去实例化我们需要的cb实例的步骤
viewHolder.deleteCheckBox.setChecked(!viewHolder.deleteCheckBox.isChecked());
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:id="@+id/widget30"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<RelativeLayout
android:id="@+id/rLayout"
android:layout_width="fill_parent"
android:layout_height="50px"
android:gravity="center_horizontal"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
>
<LinearLayout
android:id="@+id/son_lLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
>
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
/>
<TextView
android:id="@+id/tv_phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
/>
</LinearLayout>
<CheckBox
android:layout_alignParentRight="true"
android:id="@+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:checked="false"
android:focusable="false"
/>
</RelativeLayout>
</LinearLayout>
2、滑动时checkbox错位措施,首先,给checkbox设置settag:
holder.deleteCheckBox.setTag(getDataIndex().get(position).get("dataIndex").toString());
3、然后,存checkbox的check值,要注意事项:adapter每次取得一个屏幕外的item时,都会重新调用getview()里面的方法,所以加个判断:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int CheckBoxId = Integer.parseInt(buttonView.getTag().toString());
int i = -1;//保存checkboxid的值
if (isChecked) {
if(!isCheckMap.containsKey(CheckBoxId)) {//每次getview都会调用一次,所以要判断key是否已存在,防止重复put
isCheckMap.put(CheckBoxId, isChecked);
isDeleteCheckeBoxId.put(deleteKey, CheckBoxId);
isDeleteUserMessage.put(CheckBoxId, datas.get(CheckBoxId));
deleteKey++;
}
4、最后,取出checkbox的check值,一定要先由上一步存后再取出:
if (isVisible) {//当在可见状态的时候
holder.deleteCheckBox.setVisibility(View.VISIBLE);
if (isCheckMap != null && isCheckMap.containsKey(position)) {//有曾经选中过的记录
holder.deleteCheckBox.setChecked(isCheckMap.get(position));//显示为原本的选择状态
} else {
holder.deleteCheckBox.setChecked(false);//显示为没被选中的状态
}
5、注意,2、3、4的代码都是写在adapter的getview()方法里面的