我有三个单选按钮来指定性别,“男”,“女”和“其他”。根据用户选择,我将此数据保存为我的数据库中的男性1个,女性2个,其他3个。这反射(reflect)在个人资料页面中,现在,当我要编辑个人资料时,我想以可编辑的方式自动填充个人资料页面的所有字段时,用户只需更改他想要的字段即可。尽管我可以从数据库中获取性别的1,2,3值,但是我无法填充选中的指定单选按钮。我尝试了以下方法:

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);
}

最佳答案

您可以使用radioButton.setChecked(true);或radiobutton.setSelected(true);

不要给出rb1,在您的代码中rb1指的是RadioGroup,设置单选按钮的名称。

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);
}

关于android - 单选按钮通过代码设置检查状态,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12832456/

10-11 22:30
查看更多