gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:17:47 45 4
gpt4 key购买 nike

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

如果用户选择选项3我要获取索引,2.

最佳答案

你应该可以做这样的事情:

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

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

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

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

关于java - 如何在 Android 中获取 RadioGroup 的选定索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6440259/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com