一、基本使用方法:
1.在子项布局中添加CheckBox
若要为Listview添加点击监听事件,需要在CheckBox属性中添加以下两个属性
android:clickable="false"
android:focusable="false
2.在Adapter中传入子项布局即可显示
3.为CheckBox添加选中监听事件
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//写入你的处理事件
}
});
二、问题及解决方案
问题:
上滑后再下滑,发现原来选中的CheckBox变为未选中
原因:
当勾选第0个条目时,此时isCheck状态为true,滑动条目到新的条目会复用第一个条目,而此OnCheckedChangeListener还未绑定新的条目,依然会调用第0个条目的回调,因此,当往回滑动时,第0个条目的isCheck状态依然会变成false。
解决方案:(我自定义的适配器继承自ArrayAdapter)
1.首先,在Java类中添加一个boolean参数,用于判断是否被选中
Java类代码示例
public class Novel_name_path {
private boolean check;
//构造方法
public Novel_name_path(){
this.check = false;
}
//获取选中状态
public boolean getCheck(){
return this.check;
}
//设置选中状态
public void setCheck(boolean check){
this.check = check;
}
}
自定义Adapter代码示例
public class NovelAdapter extends ArrayAdapter<Novel_name_path> {
private int recourceId;
public NovelAdapter(Context context, int textViewRecourceId, List<Novel_name_path> objects){
super(context,textViewRecourceId,objects);
recourceId = textViewRecourceId;
}
@NonNull
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final Novel_name_path novel_name_path = getItem(position);
View view;
ViewHolder viewHolder;
//提升效率
if (convertView==null){
view = LayoutInflater.from(getContext()).inflate(recourceId,parent,false);
viewHolder = new ViewHolder();
viewHolder.v_box = (CheckBox)view.findViewById(R.id.check_box);
view.setTag(viewHolder);
}else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
//设置监听事件
viewHolder.v_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//设置选中状态
novel_name_path.setCheck(b);
}
});
//选中状态更新到UI中
viewHolder.v_box.setChecked(novel_name_path.getCheck());
return view;
}
class ViewHolder{
CheckBox v_box;
}
}
2.传入Adapter,第三个参数为public类型
//数据
public List<Novel_name_path> novel_name_paths = new ArrayList<>();
//传入Adapter
NovelAdapter adapter = new NovelAdapter(Importnovel.this,R.layout.list_novel,novel_name_paths);
listView.setAdapter(adapter);
问题解决~~