单选按钮集合通过代码设置选中状态

7

我有三个单选按钮用于指定性别,男性、女性和其他。根据用户选择,我将此数据保存为1表示男性,2表示女性,3表示其他,并在个人资料页面中进行反映。现在,当我想编辑个人资料时,我希望以可编辑的方式自动填充个人资料页面的所有字段,用户只需更改他想要更改的字段。虽然我能够从数据库中获取性别为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.setSelected(true); - Syn3sthete
3个回答

14
你可以使用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);
}

1
无法使用radioButton.setChecked(true)或radiobutton.setSelected(true)。 - Heretic Monk
我能够通过 toast 消息的帮助显示从数据库中获取的值! - Heretic Monk
在你的代码中删除以下行 rb1.check(R.id.radiobutton3);。 - Siva K
已删除!然后在第一个位置进行了检查,但仍无法工作! - Heretic Monk
尝试使用此代码:M.equalsIgnoreCase("2") - Siva K
是的,现在它可以工作了,感谢您的帮助!我正在检索字符串值并将它们作为整数进行检查! - Heretic Monk

2

这是用于设置选中状态的。

radioButton.setChecked(true);

这是用于获取选中单选按钮的值的代码:

RadioGroup rg=(RadioGroup) findViewById(R.id.radioGroup1);

rg.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup arg0, int id)
{
RadioButton checkedRadioButton = (RadioButton)rg.findViewById(id);

boolean isChecked = checkedRadioButton.isChecked();

if (isChecked)
{
Toast.makeText(getApplicationContext(), 
           checkedRadioButton.getText(),Toast.LENGTH_LONG).show();
}
}});

我正在从数据库中获取已选状态,伙计! - Heretic Monk

1

尝试这段代码:

radioButton.setChecked(true);

radioSexGroup = (RadioGroup) findViewById(R.id.radioSex);
int selectedId = radioSexGroup.getCheckedRadioButtonId();
rb = (RadioButton) findViewById(selectedId);
sex = rb.getText().toString().trim();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接