繁体   English   中英

在列表视图中处理选中然后未选中的复选框的值

[英]Handle checked and then unchecked checkbox's value in listview android

在我的活动中,列表视图中有4个项目,每行都有一个复选框。 离开活动后,我希望所有选中的项目位置编号都在arraylist中。 当用户单击所有复选框并退出活动时,此代码可以正常工作。 但是,当用户单击复选框然后取消选中该复选框时,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);

                }
            }
        });
    }
}

我在我的listview所在的活动中处理此适配器类。 我在这里采用这样的arraylist值

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

在itemNumber字符串中,我需要所有检查的项目编号值。

预先感谢您的指导。

请遵循以下方法。

  • 使用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

取代这个

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);

 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM