在Android开发中,添加单选组通常需要使用以下步骤:
1. 在布局文件(如activity_main.xml)中,使用`
```xml
android:id="@+id/radio_group" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="vertical"> android:id="@+id/radio_button_1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项1" /> android:id="@+id/radio_button_2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项2" /> android:id="@+id/radio_button_3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="选项3" />
```
2. 在Java代码中,获取对应的`RadioGroup`和`RadioButton`实例:
```java
RadioGroup radioGroup = findViewById(R.id.radio_group);
RadioButton radioButton1 = findViewById(R.id.radio_button_1);
RadioButton radioButton2 = findViewById(R.id.radio_button_2);
RadioButton radioButton3 = findViewById(R.id.radio_button_3);
```
3. 设置单选按钮的选中状态:
```java
// 设置某个单选按钮为选中状态
radioButton1.setChecked(true);
```
4. 单选组的选择事件:
```java
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId) {
case R.id.radio_button_1:
// 选择了第一个选项
break;
case R.id.radio_button_2:
// 选择了第二个选项
break;
case R.id.radio_button_3:
// 选择了第三个选项
break;
}
}
});
```
通过这些步骤,您就可以在Android应用中添加单选组,并根据用户的选择进行相应的操作。