[英]How to get id from dynamically added checkbox and them value
I want to get value for dynamically added CheckBox but when i want to see if one of my checkBox.isChecked();我想为动态添加的 CheckBox 获取价值,但是当我想查看我的 checkBox.isChecked(); 中是否有一个时; it only respond when i check the last checkbox created !
它仅在我检查创建的最后一个复选框时响应! Here is my container.
这是我的容器。
for (String answer : multiMap.get(questionFromMultiMap))
{
i++;
et_button = (CheckBox) getLayoutInflater().inflate(R.layout.numberofchoices, null);
et_button.setText(answer);
et_button.setId(i);
container.addView(et_button);
listOfChoice.add(answer);
}
I want to check it's checked like that :我想检查它是这样检查的:
btnCorrect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (et_button.isChecked()){
System.out.println(et_button.getId());
}else{
System.out.println("pouet");
}
}
});
Didn't find right answer on google !在谷歌上没有找到正确的答案! Thanks for help
感谢帮助
When you call et_button.isChecked() this is called on the last inflated view, cause you are overwriting it every iteration of the loop.当您调用 et_button.isChecked() 时,它会在最后一个膨胀的视图上调用,因为您在循环的每次迭代中都会覆盖它。 You should add them in a List instead, and then in the onClickListener check which one is checked:
您应该将它们添加到列表中,然后在 onClickListener 中检查选中了哪一个:
List<CheckBox> list = new LinkedList<>(); //this should be visible from onClickListener, so it should be an instance field
for (String answer : multiMap.get(questionFromMultiMap)) {
i++;
CheckBox et_button = (CheckBox) getLayoutInflater().inflate(R.layout.numberofchoices, null);
et_button.setText(answer);
et_button.setId(i);
list.add(et_button);
container.addView(et_button);
listOfChoice.add(answer);
}
btnCorrect.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
for(CheckBox cb : list) {
if (cb.isChecked()){
System.out.println(cb.getId());
}else{
System.out.println("pouet");
}
}
}
});
Haven't tested it but It should work.还没有测试它,但它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.