RadioButton 二选一的代码
时间: 2024-02-03 18:12:10 浏览: 29
RadioButton 是一个单选按钮控件,一般用于让用户在两个或多个选项中选择一个。以下是一个简单的二选一的代码示例:
```xml
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项 1" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项 2" />
</RadioGroup>
```
在这个示例中,我们创建了一个 RadioGroup,并在其中添加了两个 RadioButton。这两个 RadioButton 都属于同一个 RadioGroup,所以它们是互斥的,即用户只能选择其中的一个。
在代码中,我们可以通过监听 RadioButton 的选择事件来获取用户的选择:
```java
RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = findViewById(checkedId);
String text = radioButton.getText().toString();
// 处理用户的选择
}
});
```
在这个代码中,我们通过 setOnCheckedChangeListener 方法设置了一个监听器,当用户选择了 RadioButton 时,会触发 onCheckedChanged 方法。我们可以在这个方法中获取用户的选择,并进行相应的处理。
相关推荐
![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)