2012-11-19 43 views
0

我有一个收音机组,有2个选项,分别是男性和女性。 我想将RadioButton Male保存为int数字“1”,女性保存为我的数据库中的“2”。 但我真的不知道如何实现它。 如果有人可以在这个问题上启发我吗? 预先感谢您。如何将单选按钮文本更改为int?

<RadioGroup 
    android:id="@+id/radio_sex" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/email_address" 
    android:layout_alignTop="@+id/textView5" 
    android:orientation="vertical" > 

    <RadioButton 
     android:id="@+id/radio_male" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Male" /> 

    <RadioButton 
     android:id="@+id/radio_female" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Female" /> 
</RadioGroup> 
+0

你有没有考虑取的单选按钮的索引你RadioGroup中?如果没有,也许你需要看到这个[问题](http://stackoverflow.com/questions/6440259/how-to-get-the-selected-index-of-a-radiogroup-in-android)。 –

+0

感谢Lokesh Mehra,我在这个问题中得到了一些非常有用的信息。 –

回答

3
RadioGroup rg = (RadioGroup) findViewById(R.id.radio_sex); 
int selected = rg.getCheckedRadioButtonId(); 
RadioButton rb = (RadioButton) findViewById(selected); 
if(rb.getText().equals("Male"){ 
    //save to db number one 
}else{ 
    //save number two 
} 
2

为单选男性为1设置标签和女性为2

<RadioButton 
    android:id="@+id/radio_male" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:tag="1" 
    android:text="Male" /> 

<RadioButton 
    android:id="@+id/radio_female" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:tag="2" 
    android:text="Female" /> 

然后上选中了变化,得到了选定的单选按钮的标签,并投它为int,然后保存到数据库。

setOnCheckedChangeListener(new OnCheckedChangeListener() { 

     @Override 
     public void onCheckedChanged(RadioGroup group, int checkedId) { 
      int value=Integer.parseInt(findViewById(checkedId).getTag().toString()); 
     } 
    }); 
+0

我已经设法解决了我的问题,但仍然感谢您的答案。这给了我一个可以用来解决我的问题的替代方法。 –

2
<RadioGroup 
    android:id="@+id/radio_sex" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/email_address" 
    android:layout_alignTop="@+id/textView5" 
    android:orientation="vertical" > 

    <RadioButton 
     android:id="@+id/radio_male" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Male" /> 

    <RadioButton 
     android:id="@+id/radio_female" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Female" /> 
</RadioGroup> 

现在在你的java文件检查要么单选按钮

int maleFemaleVar = (radio_male.isChecked() ? 1 : 2); 

现在这个新maleFemaleVar保存到数据库

相关问题