我动态创建了复选框(作为 api 的响应)。现在我需要获取已选中的复选框的值。这是我的代码。
private HashMap<Integer,String> answerMap= new HashMap<>();
for (int i = 1; i <= formsData.get(position).getValues().size(); i++) {
CheckBox checkBox = new CheckBox(mContext);
Forms forms = formsData.get(position);
checkBox.setText(formsData.get(position).getValues().get(i - 1));
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
answerMap.put(formsData.get(position).getQuestionId(),checkBox.getText().toString());
} else {
answerMap.remove(formsData.get(position).getQuestionId());
System.out.println("map size: " + answerMap.size());
}
for (Map.Entry<Integer, String> entry : answerMap.entrySet()) {
Integer key = entry.getKey();
String value = entry.getValue();
System.out.println("question id : " + key + " answer : " + value);
}
}
});
但在这里,如果选中了多个复选框,我只会获取最后选中项的值。谁能帮帮我
最佳答案
在循环之前创建一个列表:ArrayList<CheckBox> array = new ArrayList<>();
每次创建复选框后,将其添加到列表中:array.add(checkBox);
现在,列表中已包含所有复选框,您可以循环浏览它们以查找已选中的复选框:
for (int i = 0; i < array.size(); i++) {
if (array.get(i).isChecked()) {
Log.i("mine", i + " is checked");
}
}
关于java - 如何获取动态创建的复选框android的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51198655/