RadioGroup单选
时间: 2024-05-09 09:15:42 浏览: 10
RadioGroup 是一个 Android UI 组件,它允许用户从一组互斥的选项中选择一个选项。它通常包含一组 RadioButton 组件,它们是相互排斥的,即只能选择其中的一个。
以下是一个简单的示例,演示如何在 XML 中创建 RadioGroup 和 RadioButton 组件,并将它们组合在一起以实现单选功能:
```
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_button_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<RadioButton
android:id="@+id/radio_button_2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
<RadioButton
android:id="@+id/radio_button_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 3" />
</RadioGroup>
```
在代码中,您可以使用以下方式获取所选的 RadioButton 的 ID:
```
RadioGroup radioGroup = findViewById(R.id.radio_group);
int selectedId = radioGroup.getCheckedRadioButtonId();
if (selectedId == R.id.radio_button_1) {
// Option 1 is selected
} else if (selectedId == R.id.radio_button_2) {
// Option 2 is selected
} else if (selectedId == R.id.radio_button_3) {
// Option 3 is selected
}
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)