是否有一个简单的方法来获得在Android中一个RadioGroup的选定索引,或者我必须使用OnCheckedChangeListener来监听变化,并有一些东西,保持选定的最后一个索引?

示例xml:

<RadioGroup android:id="@+id/group1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:orientation="vertical">
    <RadioButton android:id="@+id/radio1" android:text="option 1" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio2" android:text="option 2" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio3" android:text="option 3" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio4" android:text="option 4" android:layout_width="wrap_content" android:layout_height="wrap_content" />
    <RadioButton android:id="@+id/radio5" android:text="option 5" android:layout_width="wrap_content" android:layout_height="wrap_content" />
</RadioGroup>

如果用户选择选项3,我想获取索引2。


当前回答

 int index_selected = radio_grp.indexOfChild(radio_grp
                .findViewById(radio_grp.getCheckedRadioButtonId()));

其他回答

就用这个吧:

    int index = 2;
    boolean option3Checked = radioGroup.getCheckedRadioButtonId() == radioGroup.getChildAt(2).getId();

这是一个Kotlin扩展得到正确的位置,即使你的组包含一个TextView或任何非radiobutton。

fun RadioGroup.getCheckedRadioButtonPosition(): Int {
    val radioButtonId = checkedRadioButtonId
    return children.filter { it is RadioButton }
        .mapIndexed { index: Int, view: View ->
            index to view
        }.firstOrNull {
            it.second.id == radioButtonId
        }?.first ?: -1
}

你可以使用:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

你可以使用OnCheckedChangeListener或者使用getCheckedRadioButtonId()

你可以简单地

-在onCreate方法中声明单选组和单选按钮

private RadioGroup GrupName;
private RadioButton NameButton;

-在onCreate方法中设置视图id

GrupName = (RadioGroup) findViewById(R.id.radioGroupid);

-取选中的单选按钮id using

int id = GroupName.getCheckedRadioButtonId();

-使用id来匹配按钮选择视图

NameButton = (RadioButton) findViewById(id);

-最终得到单选按钮的值

String valueExpected = NameButton.getText().toString();

ps:如果你想要一个int值,那么你可以强制转换它

int valueExpectedIn = Integer.parseInt(valueExpected);