如何在 Android 中获取 RadioGroup 的选定索引
是否有一种简单的方法可以在 Android 中获取 RadioGroup 的选定索引,或者我是否必须使用 OnCheckedChangeListener 来侦听更改并使用某些内容来保存选定的最后一个索引?
Is there an easy way to get the selected index of a RadioGroup in Android or do I have to use OnCheckedChangeListener to listen for changes and have something that holds the last index selected?
示例 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.
if a user selects option 3
I want to get the index, 2.
你应该能够做这样的事情:
You should be able to do something like this:
int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);
如果 RadioGroup
包含其他视图(如 TextView
),则 indexOfChild()
方法将返回错误的索引.
If the RadioGroup
contains other Views (like a TextView
) then the indexOfChild()
method will return wrong index.
要在 RadioGroup
上获取选定的 RadioButton
文本:
To get the selected RadioButton
text on the RadioGroup
:
RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
String selectedtext = r.getText().toString();