如何在 Android 中获取 RadioGroup 的选定索引 [英] How to get the selected index of a RadioGroup in Android

查看:29
本文介绍了如何在 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();

这篇关于如何在 Android 中获取 RadioGroup 的选定索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆