Android 解决listview中checkBox错位选择


假如ListView,分成2页(或者设置数据可以纵向拉,可隐藏),每页3条数据,每个Listview的Item 里面有个checkBox,现在,当我选择第一页的前两天数据,翻到第二页,竟然第二页后两条数据也选中了,这是绝对不允许的。经过本人的N次调试,发现public View getView(int position, View convertView, ViewGroup parent)传进来的convertView 竟然产生多次重用。解决方案:当选中checkedBox时候,我们用一个List来保存该checkBox的position。然后在每次产生View时取得传来的convertView赋值为null,再遍历List里保存的checkBox的位置,当在数组内时,checkBox置为选中,问题解决了。

该问题有两种解决方案,个人目前所实现了的。

1.用HashMap保存checkbox的状态值。

HashMap<Integer, Boolean> state = new HashMap<Integer,Boolean>();

                     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                                // TODO Auto-generated method stub
                                if(isChecked)
                                { 
                                       state.put(position, isChecked);
                                        System.out.println("复选框以选中,选中的行数为:" + temp_position);
                                }else{
                                     state.remove(position);
                                }
                        }

在getView()方法里面: holder.cbox.setChecked(state.get(position)==null? false : true);

2.(不推荐使用,因为会产生许多垃圾对象)

public View getView(int position, View convertView, ViewGroup parent)在每次传进convertView时候,设为null。

然后每调用一次getView就产生一个view对象。

相关内容