我有一个这样的复选框:
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();
}
});