'How to programmatically uncheck a checkbox in Kotlin

I've got two checkboxes and I need to uncheck the other checkbox if the first checkbox was clicked.
Right now if a user clicks on the second checkbox and then on the first one, it works. The other way around, however, it doesn't (both of them stay checked). Any help appreciated, thanks!

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

}


Solution 1:[1]

In this case you should use RadioButtons instead of checkboxes. When you put multiple RadioButtons inside a RadioGroup, only one of them can be checked at a time, the previously selected RadioButton in that RadioGroup will be unchecked.

xml code:

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

kotlin code:

        when {
        findViewById<RadioButton>(R.id.radioButton).isChecked -> {
            //when upper button is checked
        }
        findViewById<RadioButton>(R.id.radioButton2).isChecked -> {
            //when lower button is checked
        }
    }

Solution 2:[2]

You made a simple typo. You call c1.isSelected = false, intead use c1.isChecked = false.

private fun switchCheckedBox(v : View) {
    when (v.id) {
        R.id.checkBox1 -> c2.isChecked = false
        R.id.checkBox2 -> c1.isChecked = false
    }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2