Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default checked Radio Button

I'm creating a RadioGroup with RadioButtons dynamically and need to have one radio button checked by default.

I've done this by using both radioButton.setChecked(true) and radioButton.toggle();

The problem I have is that when I at runtime select another radio button the first one stays checked so I end up with two checked radio buttons in the radio group.

Has anyone had this problem and know how to solve it?

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;
    }
like image 590
thehindutimes Avatar asked Dec 16 '13 12:12

thehindutimes


People also ask

How do I keep a radio button checked by default?

You can check a radio button by default by adding the checked HTML attribute to the <input> element. You can disable a radio button by adding the disabled HTML attribute to both the <label> and the <input> .

How can I change the default value of radio button?

This can be done using ".getElementById. And the output will be shown in a Boolean value. After clicking "Tap to check" button, it will show whether the radio button is by default clicked or not.

Should radio buttons have a default selection?

Always Offer a Default SelectionIn case of radio buttons this means that radio buttons should always have exactly one option pre-selected. Select the safest and most secure option (to prevent data loss).

How do I select a radio button by default in react?

To set the default checked value of a radio button in React: Store the radio button value in the state. Initialize the state to the value of the default checked radio button. Set the checked property on each radio button conditionally, e.g. checked={selected === 'yes'} .


1 Answers

I know I'm late but for those who search for the answer like me this can be useful.

When you add RadioButton to a RadioGroup, you must set the button checked after adding it to the parent like:

RadioGroup radioGroup = new RadioGroup(getContext())
RadioButton radioButton = new RadioButton(getContext());
radioButton.setText("text");
mRadioGroup.addView(radioButton);
radioButton.setChecked(true);

If the view is checked before adding it to the parent, it will be impossible to uncheck it.

like image 169
Sergio Carvalho Avatar answered Sep 18 '22 05:09

Sergio Carvalho