首页 > 解决方案 > 我想以编程方式添加单选按钮并设置第一个项目被选中?

问题描述

这是我的代码,我从我的 Json 创建了一堆单选按钮。

for (int i = 0; i < level_array_list.size(); i++) {
    RadioButton radioButton = new RadioButton(getActivity());
    radioButton.setText(level_array_list.get(i).getLevelName());
    radioButton.setId(Integer.parseInt(level_array_list.get(i).getLevel_id()));
    radioGrp.addView(radioButton);
}

请帮忙。提前致谢!

标签: androidjsonarraylistradio-buttonandroid-radiogroup

解决方案


我想被选中从 json 数组加载的第一个项目?

您需要在(表示第一个单选按钮)radioButton.setChecked(true);时使用内部循环i = 0

尝试这个

 for (int i = 0; i < level_array_list.size(); i++) {
            RadioButton radioButton = new RadioButton(getActivity());
            radioButton.setText(level_array_list.get(i).getLevelName());
            radioButton.setId(Integer.parseInt(level_array_list.get(i).getLevel_id()));
            if(i==0){
                radioButton.setChecked(true);
            }
            radioGrp.addView(radioButton);
        }

推荐阅读