【问题标题】:CheckBox in ListView checking the wrong item when clickedListView 中的 CheckBox 在单击时检查错误的项目
【发布时间】:2015-12-07 14:00:23
【问题描述】:

我已经通过扩展 ArrayAdapter 类实现了一个自定义列表视图,我遇到的问题是,每当我滚动列表视图时,复选框项目都未选中,所以我实现了以下代码:

CheckBox cb = (CheckBox) myview.findViewById(R.id.grocery_item_checkbox);

            //Code to keep the status of checkbox checked, when scrolling up or down
            cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

                    if(!compoundButton.isChecked()){
                        checkbox_status[pos] = false;
                        Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
                    }else{
                        checkbox_status[pos] = true;
                        Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
                    }
                    notifyDataSetChanged();
                }
            });


            if(!checkbox_status[pos]){
                cb.setChecked(false);
            }else{
                cb.setChecked(true);
            }

这里checkbox_status 是一个布尔数组,用于存储复选框的状态。而pos指的是getView方法中的位置。

我遇到的问题是,每当我单击列表视图中的顶部项目时,底部的项目就会被检查:

假设我点击位置 0 的项目,但位置 6 的项目被选中。

当我向上或向下滚动时,复选框的状态也会再次受到干扰。

【问题讨论】:

标签: android listview


【解决方案1】:

首先,您正在设置一个侦听器,然后,您正在设置选中\未选中。它触发监听器。

在那之后,我不知道你是否使用了viewholder模式。如果你不这样做,你需要使用它。否则您的问题将继续存在。

在你的适配器的 getView 方法中,你应该像下面这样实现:

//in some cases, it will prevent unwanted situations
cb.setOnCheckedChangeListener(null);


if(!checkbox_status[pos]){
    cb.setChecked(false);
}else{
    cb.setChecked(true);
}

//Code to keep the status of checkbox checked, when scrolling up or down
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
      @Override
      public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

           if(!compoundButton.isChecked()){
               checkbox_status[pos] = false;
               Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
           }else{
               checkbox_status[pos] = true;
               Log.d("LOG", "Checkbox at position" + pos + "is set to" + checkbox_status[pos]);
           }
           notifyDataSetChanged();
       }
});

【讨论】:

  • 这没有用,但我找到了另一种解决方法来解决这个问题。还是谢谢
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 2011-01-30
  • 2012-01-22
  • 1970-01-01
  • 1970-01-01
  • 2014-08-30
  • 1970-01-01
  • 2012-04-29
相关资源
最近更新 更多