android 关于在ListView 显示和隐藏checkboxes的实现。

需求:用ListView显示所有邮件信息,点击菜单按钮,进入编辑模式,各个item出现车乘客checkbox,选择后,点击删除按钮,删掉相应item.

问题描述:在继承BaseAdapter的getView方法中是用bindle,在是调用的时候,bindle.checkbox.setVisible();失效,部分item的checkbox不出现,和打勾后出现错位的现象。

解决方法:是用set记录选择了的项,在getView的时候,设置是否可见

Set selectedSet = new HashSet();
	
	class CheckeboxesChangedTrigger implements OnCheckedChangeListener{
		@Override
		public void onCheckedChanged(CompoundButton view, boolean isChecked) {
			if (isChecked) {
				selectedSet.add(view.getTag().toString());
			} else {
				selectedSet.remove(view.getTag().toString());
			}
		}
	
	}

@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view = convertView;
			if(convertView == null) {
				view = getLayoutInflater().inflate(R.layout.msg_list_item,
						null);
			}
			TextView txtUserCode = (TextView) view
					.findViewById(R.id.txtUserCode);
			TextView txtContent = (TextView) view.findViewById(R.id.txtContent);
			ImageView img = (ImageView) view.findViewById(R.id.img_msg_marker);
			CheckBox itemChecker = (CheckBox) view.findViewById(R.id.itemChecker);
			itemChecker.setTag(items.get(position).get("id"));
			itemChecker.setOnCheckedChangeListener(checkeboxesChangedTrigger);
			if(MODE == EDIT_MODE){//通过设置MODE的值,实现是否可见
				itemChecker.setVisibility(View.VISIBLE);
			}else if (MODE == NORMAL_MODE) {
				itemChecker.setVisibility(View.GONE);
			} 
			txtUserCode.setText(items.get(position).get("userCode").toString());
			txtContent.setText(items.get(position).get("msgContent").toString());
			img.setBackgroundResource((Integer) items.get(position).get("img"));
			String key = items.get(position).get("id").toString();
			
			if (key != null) {  
		        if(selectedSet.contains(key)){  //关键代码解决错位问题
		            itemChecker.setChecked(true);  
		        }else{  
		            itemChecker.setChecked(false);  
		        }  
		    }
			
			view.setTag(itemChecker);
			return view;
		}


private void changeMode(int mode){
		if(mode == MsgReadActivity.EDIT_MODE){
			navigationBar.setVisibility(View.GONE);
			toolBar.setVisibility(View.VISIBLE);
			MODE = EDIT_MODE;
		}else if (mode == MsgReadActivity.NORMAL_MODE) {
			navigationBar.setVisibility(View.VISIBLE);
			toolBar.setVisibility(View.GONE);
			MODE = NORMAL_MODE;
		}else {
			Log.e("MsgReadActivity.changeMode", "mode error :" + mode);
		}
		adapter.notifyDataSetChanged();//记得调用该方法,通知数据已发生变化
	}


你可能感兴趣的:(android 关于在ListView 显示和隐藏checkboxes的实现。)