1. 定义成员变量用于记录ListView所有item的选中状态:
private Map<Integer, Boolean> checkStatusMap = new HashMap<Integer, Boolean>();2. 在adapter初始化时候向checkStatusMap中put listView数据个数的false(false意味着一开始都是未选中):
private class CallLogListAdapter extends BaseAdapter { private Context context; private ViewItemHolder holder; private LayoutInflater inflater; public CallLogListAdapter(Context c) { this.context = c; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); int position = 0; for(int i = 0; i < recordList.size(); i++){ checkStatusMap.put(position++, false); } }
@Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { ViewItemHolder holder = (ViewItemHolder) view.getTag(); holder.contactIsDelCheckBox.toggle(); boolean isChecked = holder.contactIsDelCheckBox.isChecked(); // save CheckBox status checkStatusMap.put(position - 1, isChecked); //... }4. 在adapter的getView()方法中从checkStatusMap中获取选中
@Override public View getView(final int position, View convertView, ViewGroup parent) { if (convertView != null) { holder = (ViewItemHolder) convertView.getTag(); } else { convertView = inflater.inflate(R.layout.call_log_delete_preview_item, null); holder = new ViewItemHolder(); holder.contactTimeTextView= (TextView) convertView.findViewById(R.id.contact_time); holder.contactTypeImageView = (ImageView) convertView.findViewById(R.id.contact_type); holder.contactNumberTextView = (TextView) convertView.findViewById(R.id.contact_number); holder.contactByImageView = (ImageView) convertView.findViewById(R.id.contact_by); holder.contactDurationTextView = (TextView) convertView.findViewById(R.id.contact_duration); holder.contactIsDelCheckBox = (CheckBox) convertView.findViewById(R.id.contact_is_delete); convertView.setTag(holder); } // init holder // ...... // get checkbox check status holder.contactIsDelCheckBox.setChecked(checkStatusMap.get(position)); return convertView; }5. 如果点击了全选CheckBox,则往checkStatusMap中遍历put进入全部true 否则put进入全部false:
private void checkAllRecord(boolean isChecked){ int size = recordListView.getChildCount(); if(isChecked){ for(int i = 1; i < size; i++){ RelativeLayout layout = (RelativeLayout) recordListView.getChildAt(i); CheckBox isDel = (CheckBox) layout.findViewById(R.id.contact_is_delete); isDel.setChecked(true); } mRecordDelButton.setEnabled(true); // set all checkbox check status to be checked for(int i = 0; i < checkStatusMap.size(); i++){ checkStatusMap.put(i, true); } }else{ for(int i = 1; i < size; i++){ RelativeLayout layout = (RelativeLayout) recordListView.getChildAt(i); CheckBox isDel = (CheckBox) layout.findViewById(R.id.contact_is_delete); isDel.setChecked(false); } mRecordDelButton.setEnabled(false); // set all checkbox check status to be unchecked for(int i = 0; i < checkStatusMap.size(); i++){ checkStatusMap.put(i, false); } } }