如何获取复选框的值并保存在数组中?

How to get value of Checkbox and save in Array?

我有一个这样的复选框:

LinearLayout layout = findViewById(R.id.lyLayout);
CheckBox checkBox;

for (int i = 0; i < items.size(); i++) {
    checkBox = new CheckBox(getBaseContext());
    checkBox.setId(View.generateViewId());
    checkBox.setText(items.get(i).getDesk());
    layout.addView(checkBox); 
}

我想获取检查数据,我这样做:

ArrayList<String> checkedBox = new ArrayList<>();
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
    for (int a = 0; a < layout.getChildCount(); a++) {
        checkBox = (CheckBox) layout.getChildAt(a);
        if (checkBox.isChecked()) {
            checkedBox.add(checkBox.getText().toString());
            Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();
        } else {
            checkedBox.remove(checkBox.getText().toString());
            Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();
        }
    }
});

但捕获的数据仅在索引 0 处。除此之外,不会存储数据。有时数据根本没有存储。

尝试使用以下代码。

 private ArrayList<String> getCheckBoxData(){
     ArrayList<String> checkedBox = new ArrayList<>();
     for (int a = 0; a < layout.getChildCount(); a++) {
         checkBox = (CheckBox) layout.getChildAt(a);
         if (checkBox.isChecked()) {
              checkedBox.add(checkBox.getText().toString());
             Toast.makeText(getApplicationContext(), checkBox.getText().toString() + " checked", Toast.LENGTH_LONG).show();
         } 
     }
 return checkedBox;
 }

我已设法解决错误

我更改了我的代码:

ArrayList<String> checkedBox = new ArrayList<>();
checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> 
    {
        for (int a = 0; a < layout.getChildCount(); a++) {
        checkBox = (CheckBox) layout.getChildAt(a);
        if (checkBox.isChecked()) {
        checkedBox.add(checkBox.getText().toString());
        Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();

        } else {
            checkedBox.remove(checkBox.getText().toString());
            Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();
            }
        }
    });

对此:

checkBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
                                        if(isChecked){
                                            checkedBox.add(buttonView.getText().toString());
                                            Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();

                                        } else {
                                            checkedBox.remove(buttonView.getText().toString());
                                            Toast.makeText(getApplicationContext(), checkedBox.toString() + " checked", Toast.LENGTH_LONG).show();
                                        }
                                    });