设置默认选中的单选按钮

the*_*mes 9 android android-radiobutton

我创建一个RadioGroupRadioButton小号动态的,需要有一个单选按钮默认为选中.

我通过使用radioButton.setChecked(true)和完成了这个radioButton.toggle();

我遇到的问题是,当我在运行时选择另一个单选按钮时,第一个单选按钮保持选中状态,因此我最终在收音机组中有两个选中的单选按钮.

有谁有这个问题,知道如何解决它?

private RadioButton addRadioButton(String type, String price){
        RadioButton radio = new RadioButton(Order.this);
        radio.setText(type + " (" + Utils.formatCurrency(price) + ")");
        radio.setTextAppearance(Order.this, R.style.portalCellTextStyle);
        radio.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
        radio.setTag(price);

        if(type.toLowerCase().equals("m"))
            radio.toggle();

        return radio;
    }
Run Code Online (Sandbox Code Playgroud)

小智 10

我知道我迟到了,但对于那些像我这样寻找答案的人来说,这可能很有用.

将RadioButton添加到RadioGroup时,必须在将其添加到父组件后设置按钮,如:

RadioGroup radioGroup = new RadioGroup(getContext())
RadioButton radioButton = new RadioButton(getContext());
radioButton.setText("text");
mRadioGroup.addView(radioButton);
radioButton.setChecked(true);
Run Code Online (Sandbox Code Playgroud)

如果在将视图添加到父视图之前检查视图,则无法取消选中它.


Sil*_*ler 1

如果您只使用一个单选框来打开和关闭,也许您应该使用复选框或切换按钮。

http://developer.android.com/resources/tutorials/views/hello-formstuff.html

向下滚动并查看复选框和切换按钮。

使用收音机时,您通常有不止一台收音机,您可以在它们之间进行选择。比如简单、中等、困难。

代替

radio.toggle();
Run Code Online (Sandbox Code Playgroud)

radio.setChecked(true);
Run Code Online (Sandbox Code Playgroud)