Android获取选定单选按钮的值

27

我有一个名为rg1的RadioGroup,我想获取所选单选按钮的值。

我知道可以使用以下代码获取所选单选按钮的id:

if(rg1.getCheckedRadioButtonId()!=-1)
int id= rg1.getCheckedRadioButtonId()

这会给我按钮的id,但我想要该按钮的值。

9个回答

65
你需要获取指定索引的单选按钮,然后获取该按钮文本的值。请尝试以下代码。
if(rg1.getCheckedRadioButtonId()!=-1){
    int id= rg1.getCheckedRadioButtonId();
    View radioButton = rg1.findViewById(id);
    int radioId = radioGroup.indexOfChild(radioButton);
    RadioButton btn = (RadioButton) rg1.getChildAt(radioId);
    String selection = (String) btn.getText();
}

4
getCheckedRadioButton 返回的 id 是否只是 RadioGroup 内 RadioButton 的 id?为什么不能直接获取 RadioButton 的 id,然后使用更通用的 findViewById 来获取 RadioButton,而要额外增加 indexOfChild 和 getChildAt 这些步骤呢? - Rarw
1
radioGroup是什么?在int radioId = radioGroup.indexOfChild(radioButton)中是什么意思? - Mitesh Shah
radioGroup是RadioGroup的对象;该组包含所有单选按钮。它是这些单选按钮的父级。 - Simon Chius
所以在这种情况下,rg1和radioGroup是同一个对象,对吗? - Jack Lynx
或者您可以通过它们的ID获取单选按钮,并使用isChecked方法获取其文本(如果已选中)。像这样:RadioButton radio_male = ((RadioButton) findViewById(R.id.rbtn_male)); String gend = radio_male.isChecked() ? radio_male.getText().toString() : radio_female.getText().toString(); - vikas devde
你难道不能简单地这样做吗 - (RadioButton) rg1.findViewById(id).getText(); - Aman Grover

53

试一下这个:

RadioGroup rg = (RadioGroup)findViewById(R.id.youradio);
String radiovalue = ((RadioButton)findViewById(rg.getCheckedRadioButtonId())).getText().toString();  

谢谢,我已经得到了答案,希望我能选择多个答案作为被接受的答案:(,真的非常感谢你,你总是帮助我。 - Totti
1
谢谢你。你应该验证它是否为空,因为可能会导致应用程序崩溃。 - pess0a

3
RadioGroup rg = (RadioGroup)findViewById(R.id.youradio);
String radiovalue = (RadioButton)this.findViewById(rg.getCheckedRadioButtonId())).getText().toString();  

2

一行代码

String buisnesstype = ((RadioButton) rdtranscompany.findViewById(rdtranscompany.getCheckedRadioButtonId())).getText().toString();

1
rb1=(RadioButton)findViewById(rg1.getCheckedRadioButtonId());

现在您可以使用rb1.getText()来获取选中的Radiobutton上的文本。

0

我认为你应该尝试这个

RadioGroup rg=(RadioGroup)findViewById(R.id.youradio);
String radiovalue=(RadioButton)this.findViewById(rg.getCheckedRadioButtonId())).getText().toString();

0
RadioGroup bhktype_RadioGr = (RadioGroup)findViewById(R.id.bhkypeRadioGroup);
int flatTypeId = bhktype_RadioGroup.getCheckedRadioButtonId();
String flat_type = ((RadioButton) findViewById(flatTypeId)).getText().toString();

0
简单回答,只有一行。
View v = yourView;  // as a button

String radiovalue = (RadioButton)v).getText().toString();

0

使用这段Kotlin代码,在单选按钮组中仅在单选按钮被选中时获取单选按钮文本 -

radioGroup.setOnCheckedChangeListener { rg, i ->
    val selectedId = radioGroup.checkedRadioButtonId
    val radioButton = findViewById<RadioButton>(selectedId)
    myTextView.text = radioButton.text
}

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