首页 > 解决方案 > 如何以编程方式取消选中 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
        }
    }

}

标签: androidkotlin

解决方案


在这种情况下,您应该使用RadioButtons 而不是复选框。当您将多个RadioButtons 放入 aRadioGroup时,一次只能检查其中一个,之前选择RadioButtonRadioGroup将取消选中。

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
        }
    }

推荐阅读