如何在Android中获取RadioGroup的选定索引

是否有一种简单的方法来获取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>

如果用户选择option 3我要获取索引,则2。


蝴蝶不菲
浏览 986回答 3
3回答

Qyouu

您应该能够执行以下操作:int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();View radioButton = radioButtonGroup.findViewById(radioButtonID);int idx = radioButtonGroup.indexOfChild(radioButton);如果RadioGroup包含其他视图(如TextView),则该indexOfChild()方法将返回错误的索引。要在上获取选定的RadioButton文本RadioGroup:&nbsp;RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);&nbsp;String selectedtext = r.getText().toString();

红颜莎娜

这应该工作,int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android