选定的单选按钮,Android开值单选、按钮、开值、Android

2023-09-05 10:55:39 作者:不忘初心,一鹿同行

我有一个RadioGroup中皂苷Rg1 ,我想获得选定的单选按钮的值。

I have a RadioGroup rg1 and I want to get the value of the selected radio button.

我知道,我可以用得到选定的单选按钮的 ID

I know that I can get the id of the selected radio button by using:

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

这是给我的ID,但我想这个按钮的值。

that gives me the id , but I want the value of that button.

推荐答案

您需要获得的单选按钮索引,然后获取该按钮的文本值。试试下面这个code。

You need to get the radio button at that index, then get the value of the text of that button. Try this code below.

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();
}