【发布时间】:2021-09-04 13:53:50
【问题描述】:
我有一个这样的复选框:
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 处。除此之外,不存储数据。有时数据根本没有存储。
【问题讨论】:
-
checkBox仅指最后添加的复选框,因此您只是在最后一个上注册了一个侦听器。 -
谢谢,这对我有帮助。我终于明白错误在哪里了。
标签: java android android-studio arraylist checkbox