java - 如何以编程方式设置Checked单选按钮(动态创建的单选按钮)android
问题描述
我试试
radioButton.setChecked(true);
但它唯一有效的第四个单选按钮。我尝试动态创建单选按钮。我在 for 循环中创建单选按钮,然后存储单选按钮值。然后恢复单选按钮值(这意味着,当我选择第二个选项并保存它然后恢复它时,我有 4 个选项(setChecked 2nd option))但它只有 setChecked 4th 选项。
创建单选按钮。
for (int k = 0; k < choiceElementList.size(); k++) {
if (choiceElementList.get(k).dataFormatId == 1) {
radioButton = new RadioButton(getContext());
radioButton.setText(choiceElementList.get(k).getDataFormatValue());
radioButton.setLayoutParams(params1);
radioButton.setPadding(0, 5, 0, 5);
Log.e("setid", String.valueOf(choiceElementList.get(k).getId())) ;
radioGroup.addView(radioButton);
}
}
尝试恢复它
if(choiceElementList.get(k).getId() == Cons.Id){
radioButton.setChecked(true);
}
解决方案
首先将 ID 设置为您的RadioButtons
for (int k = 0; k < choiceElementList.size(); k++) {
if (choiceElementList.get(k).dataFormatId == 1) {
RadioButton radioButton = new RadioButton(getContext());
// Set ID to Radio Button
radioButton.setId(k);
radioButton.setText(choiceElementList.get(k).getDataFormatValue());
radioButton.setLayoutParams(params1);
radioButton.setPadding(0, 5, 0, 5);
Log.e("setid", String.valueOf(choiceElementList.get(k).getId())) ;
radioGroup.addView(radioButton);
}
}
现在只需使用您的 IDRadioGroup
来检查欲望RadioButton
if(choiceElementList.get(k).getId() == Cons.Id){
radioGroup.check(k); // K will be your ID Set for your desire RadioButton
}
快乐的编码...
推荐阅读
- api - Quickbooks API:如何使用 api 针对客人在 Quickbooks 中下的订单生成采购订单?
- docker - 运行微服务 go(未找到)
- reactjs - Ant Design:使用自定义验证器验证表单字段
- python - 如何将大型数据集上传到 AWS Elasticsearch 集群?
- hibernate - 需要了解更多关于 hibernate , JpaHIbernate & JPA
- react-native - 错误获取依赖配置失败。安装字体时
- ansible - 在 when 语句中使用 ansible 变量
- c# - 为什么没有加载类库中的图像资源?
- c# - 列表
> 不接受列表 - >?
- laravel - 方法 App\Http\Controllers\Auth\RegisterController::validator 不存在