2012-10-11 58 views
5

我有三个单选按钮来指定性别,男女和其他人。根据用户选择,我将这些数据保存到我的数据库中,其中男性为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); 
} 
+0

radiobutton.setSelected(真); – Syn3sthete

回答

11

您可以使用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); 
} 
+0

好的,让我试试这个! –

+1

不能使用radioButton.setChecked(true)也不能使用radiobutton.setSelected(true) –

+0

我可以通过Toast消息的帮助显示从数据库获取的值!在您的代码中, –

1

试试这个代码:

radioButton.setChecked(true); 

radioSexGroup = (RadioGroup) findViewById(R.id.radioSex); 
int selectedId = radioSexGroup.getCheckedRadioButtonId(); 
rb = (RadioButton) findViewById(selectedId); 
sex = rb.getText().toString().trim(); 
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(); 
} 
}}); 
+0

我正在从数据库队友中提取检查状态! –