今天我学习了ListView之checkbox错位问题解决。感觉还是很麻烦的。
好的存储这个Checkbox的方法有很多,你可以放到一个HashMap<Integer, Boolean>中,
每次初始化的时候根据postion取出对应的boolean值,然后再进行checkbox的状态设置;
而经过查找资料我发现很多大佬的做法则是在entity类中加入了一个boolean值用于判断。
代码如下:
public class ContactListAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener{ private List<Person> mData; private Context mContext; public ContactListAdapter(List<Person> data, Context context) { mData = data; mContext = context; } // 定义一个刷新数据的方法 public void changeData(List<Person> data) { mData = data; notifyDataSetChanged(); } @Override public int getCount() { return mData.size(); } @Override public Person getItem(int position) { return mData.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final int index = position; ViewHolder viewHolder; if (convertView == null) { convertView = LayoutInflater.from(mContext).inflate( R.layout.item_contact, parent, false); viewHolder = new ViewHolder(); viewHolder.ly = (RelativeLayout) convertView .findViewById(R.id.lyContactListItem); viewHolder.txtName = (TextView) convertView .findViewById(R.id.txtName); viewHolder.txtNumber = (TextView) convertView .findViewById(R.id.txtNumber); viewHolder.cbxStatus = (CheckBox) convertView .findViewById(R.id.cbxStatus); convertView.setTag(viewHolder); viewHolder.cbxStatus.setTag(index); } else { viewHolder = (ViewHolder) convertView.getTag(); } viewHolder.cbxStatus.setOnCheckedChangeListener(this); viewHolder.cbxStatus.setChecked(mData.get(position).getcheckStatus()); viewHolder.txtName.setText(mData.get(index).getName()); viewHolder.txtNumber.setText(mData.get(index).getNumber()); return convertView; } @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { int index = (int)buttonView.getTag(); if (isChecked) mData.get(index).setCheckStatus(true); else mData.get(index).setCheckStatus(false); } private class ViewHolder { RelativeLayout ly; TextView txtName; TextView txtNumber; CheckBox cbxStatus; } }
今天只解决了这个问题。