Android中ListView包含CheckBox时滑动丢失选中状态的解决

现象:listview 中,如果有10项,其中手机屏幕显示1-6项,其余的7-10项在屏幕中不可见,得向下滚动后才能看到,这个时候,如果选中1、2项,再滚动到7-10项,之后再滚动回来1-6项,就发现1、2项并未被选中。

解决方法: 编写自定义的Adapter

  1. public class TestAdapter extends ArrayAdapter<String> {  
  2.     private int resource;  
  3.     private LayoutInflater inflater;  
  4.     private boolean[] checks; //用于保存checkBox的选择状态  
  5.   
  6.     public TestAdapter(Context context, int resource, List<String> list) {  
  7.         super(context, resource, list);  
  8.         checks = new boolean[list.size()];  
  9.         this.resource = resource;  
  10.         inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  11.     }  
  12.   
  13.     @Override  
  14.     public View getView(int position, View convertView, ViewGroup parent) {  
  15.         ViewHolder holder = null;  
  16.         if(convertView == null){  
  17.             convertView = inflater.inflate(resource, null);  
  18.             holder = new ViewHolder();  
  19.             holder.title = (TextView) convertView.findViewById(R.id.title);  
  20.             holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);  
  21.             convertView.setTag(holder);  
  22.         }else {  
  23.             holder = (ViewHolder) convertView.getTag();  
  24.         }  
  25.         holder.title.setText(getItem(position));  
  26.         final int pos  = position; //pos必须声明为final  
  27.         holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){  
  28.             @Override  
  29.             public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {  
  30.                 checks[pos] = isChecked;  
  31.             }});  
  32.         holder.checkBox.setChecked(checks[pos]);  
  33.         return convertView;  
  34.     }  
  35.     static class ViewHolder {  
  36.         TextView title;  
  37.         CheckBox checkBox;  
  38.     }  
  39. }  

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值