kotlin radiobutton 互斥
时间: 2024-06-23 16:00:56 浏览: 8
在 Kotlin 中,RadioButtons(单选按钮)默认就是互斥的,也就是说,一次只能选择其中的一个。当用户点击一个RadioButton时,其他已经被选中的RadioButton会自动取消选中状态。这是因为RadioButton通常在同一个RadioGroup中使用,RadioGroup内部的RadioButton是通过`android:exclusive="true"`属性设置为互斥的。
当你创建 RadioGroup 时,可以这样做:
```kotlin
val radioButtonGroup = RadioButton(this)
radioButtonGroup.group = radioGroup // 将 RadioButton 添加到 RadioGroup
val radioButton1 = RadioButton(radioButtonGroup.context)
radioButton1.text = "Option 1"
radioButton1.id = R.id.radioButton1
// 添加到 RadioGroup
radioButtonGroup.addView(radioButton1)
val radioButton2 = RadioButton(radioButtonGroup.context)
radioButton2.text = "Option 2"
radioButton2.id = R.id.radioButton2
// 添加到 RadioGroup
radioButtonGroup.addView(radioButton2)
```
然后在 XML 文件中,你可以定义 RadioGroup 并设置 `android:exclusive="true"` 属性:
```xml
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:exclusive="true">
<!-- your radio buttons here -->
</RadioGroup>
```
如果你需要自定义互斥行为或者有特殊需求,还可以在代码中监听 `onCheckedChangeListener` 来控制状态切换:
```kotlin
radioButtonGroup.setOnCheckedChangeListener { _, checkedId ->
when (checkedId) {
R.id.radioButton1 -> radioButton2.isChecked = false
R.id.radioButton2 -> radioButton1.isChecked = false
else -> // 处理未选中的情况
}
}
```