有没有一种简单的方法可以在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>

如果用户 Select option 3,我想要获取索引,2.

推荐答案

你应该能够做到以下几点:

int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();
View radioButton = radioButtonGroup.findViewById(radioButtonID);
int idx = radioButtonGroup.indexOfChild(radioButton);

如果RadioGroup包含其他视图(如TextView),那么indexOfChild()方法将返回错误的索引.

要在RadioGroup上获取选定的RadioButton个文本:

 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);
 String selectedtext = r.getText().toString();

Java相关问答推荐

ActivityCompat.请求收件箱自动拒绝权限

使用ExecutorService时在ThreadFactory中触发自定义newThread函数

Java 22模式匹配不适用于记录模式匹配.给出汇编问题

为什么接口中的主函数而不是类中的主函数在Java 17中编译和运行没有问题?

在Java 8之后,HashMap的最坏情况下时间复杂度仍然是O(n)而不是O(log n)?

当我用OkHttpClient重写shouldInterceptRequest来发布数据时,Android WebView正在以纯HTML加载URL内容

在Java中测试DAO方法:假实现与内存数据库

调用引发泛型异常的泛型方法时出现编译错误

无法初始化JPA实体管理器工厂:无法确定为Java类型<;类>;推荐的JdbcType

带错误BER验证的itext8签名返回pdf

如何集成语义发布和BitBucket(Java项目)

在向WebSphere中的文档添加元素时iText挂起

为什么Collectors.toList()不能保证易变性

try 使用类来包含JSON响应

Java创建带有扩展通配符的抽象处理器

从LineChart<;字符串、字符串和gt;中删除数据时出现特殊的ClassCastException;

循环不起作用只有第一个元素重复

为什么项目名称出现在我的GET请求中?

在数组中查找素数时出现逻辑错误

";重复键的值提示唯一约束«;livre_genre_pkey»";例外