Android 两个单选框显示其中一个选中的选择信息 
时间: 2023-05-11 19:01:51 浏览: 25
可以使用 RadioGroup 和 RadioButton 实现。首先在布局文件中添加一个 RadioGroup,然后在其中添加两个 RadioButton,分别设置不同的文本和 id。接着在代码中获取 RadioGroup 的实例,并设置 OnCheckedChangeListener,当选中的 RadioButton 发生变化时,就会触发该监听器,我们可以在其中获取选中的 RadioButton 的 id,然后根据 id 来获取选中的文本信息。
示例代码如下:
布局文件:
```
<RadioGroup
android:id="@+id/radio_group"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radio_button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项1" />
<RadioButton
android:id="@+id/radio_button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项2" />
</RadioGroup>
```
Java 代码:
```
RadioGroup radioGroup = findViewById(R.id.radio_group);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = findViewById(checkedId);
String text = radioButton.getText().toString();
Log.d("TAG", "选中的是:" + text);
}
});
```
当选中其中一个 RadioButton 时,就会在 Logcat 中输出选中的文本信息。
相关推荐











