public class Myadapter extends BaseAdapter{
private Context context;
private List<String> list;
private Map<Integer,Boolean> map= new HashMap<>();
public Myadapter(Context context, List<String> list) {
this.context = context;
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int i) {
return list.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view= LayoutInflater.from(context).inflate(R.layout.item,null);
CheckBox cb = view.findViewById(R.id.cb);
cb.setText(list.get(i));
//获取点击事件
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//如果等于true就是选中
if(b==true){
//把状态保存到Map集合中
map.put(i,true);
}else{
//反之移除
map.remove(i);
}
}
});
//判断如果map集合不为空并且key值有状态就让对应的key值显示状态
if(map!=null&&map.containsKey(i)){
cb.setChecked(true);
}else{
//反之不显示
cb.setChecked(false);
}
return view;
}
}