【问题标题】:Handle checked and then unchecked checkbox's value in listview android在listview android中处理选中然后未选中复选框的值
【发布时间】:2016-05-10 13:55:47
【问题描述】:

在我的活动中,列表视图中有 4 个项目,每行都有复选框。离开活动后,我想要一个数组列表中的所有检查项目位置编号。当用户单击所有复选框并离开活动时,此代码工作正常。但是当用户单击一个复选框然后取消选中它时,项目位置是 arraylist 无法清除。这种方法在我的 CustomAdapter 类中。

class GameAdapter extends BaseAdapter{
      private ArrayList<Integer> positions = new ArrayList<Integer>();

      public ArrayList<Integer> getPositions() {
          return positions;
      }

      getView(....){
         final ViewHolder holder;
         holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                if(holder.checkBox.isChecked()) {

                    positions.add(position);

                }
            }
        });
    }
}

我在我的列表视图所在的活动中处理这个适配器类。我正在使用这样的数组列表值

ArrayList<Integer> gamePositions = mGameAdapter.getPositions();
String itemNumbers = gamePositions.toString();

在 itemNumber 字符串中,我想要所有选中的项目编号值。

提前感谢您的指导......

【问题讨论】:

  • 检查时将值添加到数组中,但取消检查时从不删除它们

标签: java android android-layout listview checkbox


【解决方案1】:

替换这个

if(holder.checkBox.isChecked()) {

  positions.add(position);
}

有了这个

 if(holder.checkBox.isChecked()) {
     if(!positions.contains(position))
        positions.add(position);

 } else {
     if(positions.contains(position))
         positions.remove(position);

 }

【讨论】:

  • 你好......它工作但现在的问题是当我点击一个复选框并取消选中它时它会给出“不幸的是应用程序停止”错误但是当我选中它并在选中另一个复选框后取消选中它没有.. ..有点绕口令:-P 但希望你能理解..如果不清楚,请告诉我,我会再次描述..
  • java.lang.IndexOutOfBoundsException: Invalid index 2, size is 1, 这是当我检查第二项并取消选中它时...
  • 您确定异常显示了这些行之一吗?
【解决方案2】:

遵循以下方法。

  • 使用 HashMap 代替 Arraylist,如下所示

      HashMap<Integer,Boolean> mapOfSelection = new HashMap<>();
    
  • onClick 方法之前,将position 分配给复选框,如下所示。

     holder.checkbox.setTag(position);
    
  • 在 onClick 中,执行以下操作。

        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    
            mapOfSelection.put((Integer)buttonView.getTag(),isChecked); // True if this position/value is checked, false otherwise.
        }
    
  • 现在,当您需要选择的项目时,只需遍历哈希图并检查具有 True 值的 positions/Key

【讨论】:

  • 我这样做了,但是当我取消选中该项目时应用程序停止。
  • 再次查看答案,修改。这是更好的方法。你会得到解决的。
  • YW,请确保您的方法不会出现问题,因为 arrayList.remove() 有两个定义,一个用于 remove(position/Integer),另一个用于 remove(Object),您也有对象/值作为整数,它可能会导致大型数据集出现问题,因为 List 无法识别您是为位置还是为对象调用 Remove。
  • 是的,我只想将位置编号作为字符串发送到名为字符串的“联盟”中。
  • 当然,不过要小心。
猜你喜欢
  • 1970-01-01
  • 2011-07-31
  • 1970-01-01
  • 1970-01-01
  • 2015-08-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-06
  • 2018-07-25
相关资源
最近更新 更多