Check listener not being called on checkbox when isChecked set to true

36 views Asked by At

I have a condition where I need to execute the code in checkChangeListener directly without clicking on checkbox. I have set the checkbox.isChecked = true but still my checkChangeListener is not being called and the code I want to execute isn't being called. I am not sure, but setting isChecked=true should call setOnCheckedChangeListener of the checkBox. Also perform click is not working Can any one please help with this one.

Code:

if (someCondition) 
{
    checkBox.isChecked = true
}


binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
    Timber.d("check change called..............................")
    //some code to be executed directly
}


checkBox.setOnTouchListener { _, event ->
    if (event.action == MotionEvent.ACTION_UP) {
        val isChecked = checkBox.isChecked
        if (isSelectionEnabled || (!isSelectionEnabled && isChecked)) {
            binding.checkBox.isChecked =
            !binding.checkBox.isChecked
        }
    }
    true
}
1

There are 1 answers

3
Samuel On

If you need to execute the code in the setOnCheckedChangeListener block without relying on user interaction, you can manually call the listener's code after setting the isChecked property. Here's an example:

if (someCondition) {
    binding.checkBox.isChecked = true
    // Manually trigger the listener code
    binding.checkBox.setOnCheckedChangeListener { _, isChecked ->
        Timber.d("check change called..............................")
        // Some code to be executed directly
    }.onCheckedChanged(binding.checkBox, true)
}