android - 如何以编程方式取消选中 Kotlin 中的复选框
问题描述
我有两个复选框,如果单击第一个复选框,我需要取消选中另一个复选框。
现在,如果用户单击第二个复选框,然后单击第一个复选框,它就可以工作。然而,反过来却没有(它们都保持检查状态)。任何帮助表示赞赏,谢谢!
class UploadFragment : Fragment() {
lateinit var c1 : CheckBox
lateinit var c2 : CheckBox
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.fragment_upload, container, false)
c1 = view.findViewById(R.id.checkBox1)
c2 = view.findViewById(R.id.checkBox2)
c1.setOnClickListener { v -> switchCheckedBox(v) }
c2.setOnClickListener { v -> switchCheckedBox(v) }
return view
}
private fun switchCheckedBox(v : View) {
when (v.id) {
R.id.checkBox1 -> c2.isChecked = false
R.id.checkBox2 -> c1.isSelected = false
}
}
}
解决方案
在这种情况下,您应该使用RadioButton
s 而不是复选框。当您将多个RadioButton
s 放入 aRadioGroup
时,一次只能检查其中一个,之前选择RadioButton
的RadioGroup
将取消选中。
xml代码:
<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
<RadioButton
android:id="@+id/radioButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="RadioButton" />
</RadioGroup>
科特林代码:
when {
findViewById<RadioButton>(R.id.radioButton).isChecked -> {
//when upper button is checked
}
findViewById<RadioButton>(R.id.radioButton2).isChecked -> {
//when lower button is checked
}
}
推荐阅读
- typescript - 用 RxJS 依次执行 observable,concat vs concatMap
- python-3.x - 在 python tkinter 的弹出窗口中放大图像
- java - 通过 Scala Spark 读取动态 Yaml 文件
- wildfly - keycloak rest api查询是否有Not条件
- angular - SCSS 中的 Angular Image 引用被复制到 dist 的根目录
- symfony - EasyAdminBundle - 按角色和组列出的用户列表
- encryption - IIS 10 - TLS 1.2(服务器没有偏好)
- prestashop - 产品 ID 时显示文本
- java - 如何在 Spring Cloud Stream 配置中更改所有 RabbitMQ 消费者的默认恢复间隔?
- angular - 从外部 REST api 获取并显示实时数据