在ListView中放入checkbox ,是很常见的,比如微信里添加群的时候,要挨个添加联系人。相信很多人都遇到过选中checkBox 状态混乱的情况。
好了,不废话,直接上代码;
public class CheckBoxAdapter extends BaseAdapter{
private List<String> list = new ArrayList<String>();
private LayoutInflater inflater;
HashMap<Integer, Boolean> isSelected = new HashMap<Integer, Boolean>();
public CheckBoxAdapter(Context c)
{
inflater = LayoutInflater.from(c);
for(int i = 0;i<100;i++)
{
list.add(i+"");
isSelected.put(i, false);
}
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
final int pos = position ;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(
R.layout.list_index_item, null);
holder.name = (TextView) convertView
.findViewById(R.id.contact_name);
holder.Alpha = (TextView) convertView
.findViewById(R.id.contact_alpha);
holder.header = (TextView) convertView
.findViewById(R.id.contact_header);
holder.check = (CheckBox)convertView
.findViewById(R.id.check);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.header.setText(list.get(position));
holder.name.setText(list.get(position));
holder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton arg0, boolean isCheck) {
// TODO Auto-generated method stub
if(isCheck)
{
holder.check.setChecked(true);
isSelected.put(pos, true);
}
if(!isCheck)
{
holder.check.setChecked(false);
isSelected.put(pos, false);
}
}
});
if(isSelected.get(position))
{
holder.check.setChecked(true);
}else
{
holder.check.setChecked(false);
}
return convertView;
}
class ViewHolder {
TextView name;
TextView Alpha;
TextView header;
CheckBox check ;
}
}
布局文件就不上传了,核心就是用HashMap<Integer, Boolean> isSelected,去保存每个Item 的状态。初始化默认值,都是不选中,这点不能忘记,其次是选中的时候,要附上true ,否则false。还有一点,一定要在checkbox的触发事件后面写上状态是否被选中的逻辑否则会有问题。
HashMap效率较低,使用优化过的数据集合SparseArray来替代HashMap<Integer, Object>类型,上面把HashMap<Integer, Boolean> isSelected = new HashMap<Integer, Boolean>();这句替换成SparseArray<Boolean> isSelected = new SparseArray< Boolean>();即可。