Android中ListView数据不止一页,滑动后CheckBox丢失选中状态



在adapter使用全局变量保存选中状态,参考以下写法。

@Override
 public View getView(int position, View convertView, ViewGroup parent) {
  Role bean = list.get(position);
  ViewHolder holder = null;
  if(convertView == null){
   convertView = inflater.inflate(resourceId,null);
   
   holder = new ViewHolder();
   holder.ID    = (TextView) convertView.findViewById(R.id.role_id);
   holder.roleName = (TextView) convertView.findViewById(R.id.role_name);
   holder.check    = (CheckBox) convertView.findViewById(R.id.role_check);
   convertView.setTag(holder);
  }else{
   holder = (ViewHolder)convertView.getTag();
  }
  holder.roleName.setText(bean.getName());
  holder.ID.setText(String.valueOf(bean.getId()));
  
  final int posi = position; // posi必须声明为final
  holder.check.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView,
      boolean isChecked) {
     list.get(pos).setChoosed(isChecked);
    }
   });

  
  holder.check.setChecked(bean.isChoosed());
  return convertView;
 }

你可能感兴趣的:(Android)