如何将单选按钮文本更改为int?

时间:2012-11-19 08:51:02

标签: android radio-button radio-group

我有一个广播组,有2个选项,分别是男性和女性。 我想将RadioButton Male保存为int数字“1”,将Female保存为“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>

3 个答案:

答案 0 :(得分: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
}

答案 1 :(得分:2)

将单选按钮Male的标记设置为1,将female设置为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" />

然后oncheckedchanged,获取所选单选按钮的标记并将其转换为int,然后保存到数据库。

 setOnCheckedChangeListener(new OnCheckedChangeListener() {

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

答案 2 :(得分: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保存到您的数据库