android+studioradiogroup横
时间: 2023-12-04 22:41:37 浏览: 36
以下是一个在Android Studio中使用RadioGroup实现横向排列的例子:
1.在XML布局文件中添加RadioGroup和RadioButton控件,并设置orientation属性为horizontal,如下所示:
```xml
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
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" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="选项3" />
</RadioGroup>
```
2.在Java代码中获取RadioGroup控件,并设置监听器,如下所示:
```java
RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton radioButton = findViewById(checkedId);
Toast.makeText(MainActivity.this, "你选择了:" + radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
```
以上代码实现了一个横向排列的RadioGroup,并且在用户选择不同的选项时会弹出一个Toast提示用户选择的选项。