为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

蝴蝶不菲 2019-12-10 10:17:06
是否有一种简单的方法来获取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。
查看完整描述

3 回答

?
Qyouu

TA贡献1786条经验 获得超11个赞

您应该能够执行以下操作:


int radioButtonID = radioButtonGroup.getCheckedRadioButtonId();

View radioButton = radioButtonGroup.findViewById(radioButtonID);

int idx = radioButtonGroup.indexOfChild(radioButton);

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


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


 RadioButton r = (RadioButton) radioButtonGroup.getChildAt(idx);

 String selectedtext = r.getText().toString();


查看完整回答
反对 回复 2019-12-10
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

这应该工作,


int index = myRadioGroup.indexOfChild(findViewById(myRadioGroup.getCheckedRadioButtonId()));


查看完整回答
反对 回复 2019-12-10
  • 3 回答
  • 0 关注
  • 956 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信