How to programmatically select RadioButton in an activity

被刻印的时光 ゝ 提交于 2019-12-22 04:12:22

问题


In my project, I get the value of the gender from the database as 0 and 1.
0 for male and 1 for female.
Based on this values, I need to check the corresponding RadioButton in a RadioGroup.
If 0 is pressed, radio0 will be checked or radio1 will be checked.
I don't know how to check the radio button based on this string values...
This is the code I tried:

      String gendd=ViewProfileActivity.participantview.get(4);
      System.out.println("Gender:::::"+gendd);

      male=(RadioButton)findViewById(R.id.radio0);
       female=(RadioButton)findViewById(R.id.radio1);
       if(gendd.equals("0")){

           male.setSelected(true);
           female.setSelected(false);
       }
       else
           {
           male.setSelected(false);

           female.setSelected(true);

           }

But it fails. Can anyone help me?


回答1:


Try this.

   if(gendd.contains("0"))
    {
       male.setChecked(true);
       female.setChecked(false);
   }
   else
   {
       male.setChecked(false);
       female.setChecked(true);
  }



回答2:


You shoud use check(radioButtonId) method on parent RadioGroup.

E.g.

radioGroup.check(gendd.equals("0") ? R.id.radio0 : R.id.radio1);

(assuming the comparison holds as the types haven't been mentioned)



来源:https://stackoverflow.com/questions/20858929/how-to-programmatically-select-radiobutton-in-an-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!