【问题标题】:Store Selected CheckBox values in String array将选定的复选框值存储在字符串数组中
【发布时间】:2019-10-19 18:50:09
【问题描述】:

我有一个自定义对话框,它包含一个 Recylerview + SearchView 的 CarBodyColorsNames。还有一件事我有适配器,每个项目都有一个自定义行。自定义行由一个 Imagview(icons)、TextView(colorName) 和用于选择的复选框组成。它工作正常,但问题是,我想根据其适配器位置存储用户在字符串数组中检查的所有值。以下是我的代码:

edBodyColorAdapter.java

holder.checkBoxColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {


                if(isChecked)
                {
                    int position = holder.getAdapterPosition();
                    clickedColorNamePosition = edBodyColorArrayList.indexOf(filteredArrayList.get(position));

                    Toast.makeText(context, "current position = " + clickedColorNamePosition, Toast.LENGTH_SHORT).show();
                    String name = edBodyColorArrayList.get(clickedColorNamePosition).getBodyColorName();

                    Toast.makeText(context, "name = " + name, Toast.LENGTH_SHORT).show();


                }
                else
                {
                    Toast.makeText(context, "Unchecked", Toast.LENGTH_SHORT).show();
                }


            }
    });

当用户点击 Ok 按钮时我想要简单的我想要选择所有选中的复选框值。

【问题讨论】:

  • 如果用户再次按下相同的复选框会发生什么?那么,在这种情况下,您将不得不删除该值字符串数组?
  • Kishan Maurya ai 不知道如何处理这个问题。 ArrayList 是更好的选择。先生请给我解决方案的代码....tnxs提前
  • 如果您的问题得到解决,请告诉我
  • 希望对您有所帮助:stackoverflow.com/a/36597344
  • Kishan Maurya 非常感谢您为我工作......

标签: android


【解决方案1】:

全局声明1个Hashmap,用于将选中/未选中的值作为用户选中/未选中Checkbox放置/移除

HashMap<Integer, String> selectionMap = new HashMap<>();

现在在您的代码中,

holder.checkBoxColor.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    int position = holder.getAdapterPosition();
                    clickedColorNamePosition = edBodyColorArrayList.indexOf(filteredArrayList.get(position));
                    String name = edBodyColorArrayList.get(clickedColorNamePosition).getBodyColorName();
                //this mthod will check if selected checkbox value is already present or not. It present then remove ( means user unchecked box) and if value is not there means user has selected checkbox
                checkAndRemove(position,name);
            }
    });

此方法用于从 hashmap 中放置或删除值。

private void checkAndRemove(int position, String name) {
        if(selectionMap.containsKey(position)){
            selectionMap.remove(position);
        }else {
            selectionMap.put(position, name);
        }
    }

现在用户单击确定按钮后,然后使用此哈希图获取选定的值。 遍历 hashmap 值集,您将获得所有选定的值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多