android - 动态添加的 RadioButtons 不监听 onCheckChangedListener()
问题描述
我需要动态添加 RadioGroups 和 RadioButtons 并生成所需的视图并在我动态创建的 RadioGroup 上实现 onCheckChangedListener() 。问题是,当一个新添加的按钮被选中时,当我点击其他按钮时它并没有被取消选中。我已经检查了这个 -动态添加单选按钮时单选组中的问题,但无济于事。
我正在处理一个片段并在其中动态添加视图。单选按钮不显示检查更改行为。请帮我解决这个问题。
//optionsGroup(RadioGroup),optionButton(RadioButton)
optionsGroup = new RadioGroup(getActivity());
optionsGroup.setId(radioGroupCount);
optionsGroup.setPadding(20, 20, 20, 20);
optionsGroup.setLayoutParams(layparams);
radioGroupList.add(optionsGroup);
ArrayList<Options> RadioButtonOptions = question.getQuestionOptions().getOptions();
for (int i = 0; i < RadioButtonOptions.size(); i++) {
optionButton = new RadioButton(getActivity());
optionButton.setId(i);
optionButton.setText(RadioButtonOptions.get(i).getOptionValue());
optionsGroup.addView(optionButton);
optionsGroup.clearCheck();
}
optionsGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for(int rb=0;rb<optionsGroup.getChildCount();rb++){
RadioButton btn = (RadioButton) optionsGroup.getChildAt(rb);
if(checkedId==btn.getId()){
radioGroupAnswerList.clear();
radioGroupAnswerList.add(btn.getText().toString());
return;
}
}
}
});
holderlayout.addView(optionsGroup);
解决方案
如果单击了一个单选按钮,您需要取消选中其他单选按钮吗?所有这一切都将动态创建单选按钮和单选组..然后你必须这样做..
//optionsGroup(RadioGroup),optionButton(RadioButton)
optionsGroup = new RadioGroup(getActivity());
optionsGroup.setId(radioGroupCount);
optionsGroup.setPadding(20, 20, 20, 20);
optionsGroup.setLayoutParams(layparams);
radioGroupList.add(optionsGroup);
ArrayList<Options> RadioButtonOptions = question.getQuestionOptions().getOptions();
for (int i = 0; i < RadioButtonOptions.size(); i++) {
optionButton = new RadioButton(getActivity());
optionButton.setId(i);
optionButton.setText(RadioButtonOptions.get(i).getOptionValue());
optionsGroup.addView(optionButton);
optionsGroup.clearCheck();
}
optionsGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
for(int rb=0;rb<optionsGroup.getChildCount();rb++){
RadioButton btn = (RadioButton) optionsGroup.getChildAt(rb);
if(checkedId==btn.getId()){
radioGroupAnswerList.clear();
radioGroupAnswerList.add(btn.getText().toString());
optionsGroup.clearCheck();
if (isChecked) {
optionsGroup.check(btn.getId());
}
return;
}
}
}
});
holderlayout.addView(optionsGroup);
推荐阅读
- gunicorn - 为什么我最新的 cloudrun 版本没有收到流量?
- next.js - 服务器错误错误:元素类型无效:应为字符串
- google-cloud-platform - 谷歌云视频智能
- flutter - 如何调用无状态小部件的重建?
- javascript - Javascript 需要一个基本的语法解释
- google-bigquery - GA4 BigQuery 每日将“device.operating_system”字段报告值导出为“WEB”
- mysql - 在 MySQL 5.7 中对“孤岛”进行分组
- java - 是否可以使用 Kafka 将 Java 对象发送到 C# App
- c - 当我输入一个数字时,我的程序开始工作
- javascript - updateMany 具有不同的值 MongoDB