2012-10-11 59 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

我正在從數據庫隊友中提取檢查狀態! –