Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Radio Buttons Set checked state through code

I have three Radio buttons to specify the gender, Male Female and Others. I save this data into my DB as 1 for Male, 2 for female and three for others based on user selection. This is reflected in the profile page, now when I want to edit the profile I want to auto-populate all the fields of my profile page in an editable manner, the user only changes the fields he wants to. Although I am able to fetch the values of 1,2,3 for gender from my database but I am not able to populate the specified radio button as checked. I tried the following:

String M = (c.getString(c.getColumnIndexOrThrow("Gender")));
RadioGroup rb1 = (RadioGroup)findViewById(R.id.radiogroup1);

if(M.equals(1)){
    rb1.check(R.id.radiobutton3);
    RadioButton rbu1 =(RadioButton)findViewById(R.id.radiobutton3);
    rbu1.setChecked(true);
}
else if(M.equals(2)){
    rb1.check(R.id.radiobutton4);
    RadioButton rbu2 =(RadioButton)findViewById(R.id.radiobutton4);
    rbu2.setChecked(true);
}
else if(M.equals(3)){
    rb1.check(R.id.radiobutton5);
    RadioButton rbu3 =(RadioButton)findViewById(R.id.radiobutton5);
    rbu3.setChecked(true);
}
like image 486
Heretic Monk Avatar asked Oct 11 '12 04:10

Heretic Monk


People also ask

How do I mark a radio button as checked?

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 do you check radio button is checked or not in typescript?

querySelectorAll('input[type="radio"]:checked'); var value = radios.


1 Answers

You can use either radioButton.setChecked(true); or radiobutton.setSelected(true);

Don't give rb1, here in your code rb1 refers to RadioGroup, set names for radio buttons.

String M = "3";
RadioGroup rb1 = (RadioGroup)findViewById(R.id.radioGroup1);
RadioButton rbu1 =(RadioButton)findViewById(R.id.radio0);
RadioButton rbu2 =(RadioButton)findViewById(R.id.radio1);
RadioButton rbu3 =(RadioButton)findViewById(R.id.radio2);

if(M.equalsIgnoreCase("1"))
{
    rbu1.setChecked(true);
}
else if(M.equalsIgnoreCase("2")){

    rbu2.setChecked(true);
}
else if(M.equalsIgnoreCase("3"))
{    
    rbu3.setChecked(true);
}
like image 200
Siva K Avatar answered Oct 19 '22 04:10

Siva K