ListView里的CheckBox选中后滑动时候选择错位,checkbox其他checkbox也被同时选中的问题

今天在项目中ListView显示的子组件中包含复选框checkBox,运行起来发现类两个问题。

例如,第一屏能显示五个checkBox,第二屏显示6-10的checkBox,

问题1、我选中了第一个checkbox,但是屏的的第一个(也就是第六个)checkbox也被同时选中。

  我选中第二个,第七个就被选中。

问题2、选中几个checkBox后,多次滑动ListView,滑动过程中会发现被选中的checkBox发生错位。

解决方案:我们用一个List来保存该checkBox的position和选中状态。在getView()方法中通过记录List的值设置为选中状态。


public class ProcessListAdapter extends BaseAdapter {


    //1、用于记录listView中的复选框有哪些是被选中的
    HashMap<Integer, Boolean> state = new HashMap<Integer,Boolean>();

    @Override
    public View getView(final  int position, View convertView, ViewGroup parent) {

        ViewHolder holder = null;

        if (convertView == null) {
            holder = new ViewHolder();
            convertView = inflater.inflate(R.layout.item_enter_list, null);
            holder.content0 = convertView.findViewById(R.id.name);
            holder.selectCheckBox = convertView.findViewById(R.id.selectCheckBox);
            holder.content1 = convertView.findViewById(R.id.left);
            holder.content2 = convertView.findViewById(R.id.enter);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        //2、根据state设置复选框是否被选中
        //但是由于setChecked方法会触发下面setOnCheckedChangeListener,这显然不是我们要的
        //所以需要在setOnCheckedChangeListener中添加一句话,判断是用户点击的才触发
        holder.selectCheckBox.setChecked(state.get(position)==null? false : true);
        holder.selectCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                // TODO Auto-generated method stub
                //3、忽略不是认为点击 
                if(!buttonView.isPressed())return;
                //4、记录那些复选框被选中,保存在List<map>中
                if (isChecked) {
                    state.put(positionTemp, isChecked);
                } else {
                    state.remove(positionTemp);
                }

                if (isChecked) {} else {}

            }
        });
        return convertView;
    }
}

解释:重点是注释的四句话

1、用于记录listView中的复选框有哪些是被选中的
HashMap<Integer, Boolean> state = new HashMap<Integer,Boolean>();

2、在getView方法中根据state设置复选框是否被选中
 holder.selectCheckBox.setChecked(state.get(position)==null? false : true);


3、在checkBox舰艇上事件中,记录哪些复选框被选中,保存在List<map>中
if (isChecked) {
      state.put(positionTemp, isChecked);
} else {
      state.remove(positionTemp);
}

4、holder.selectCheckBox.setChecked会触发点击监听事件,忽略不是认为点击 
if(!buttonView.isPressed())return;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值