How to receive a event on android checkbox check change?

AndroidEventsCheckbox

Android Problem Overview


What would be the correct way of receiving and sending an event when a check box gets enabled or disabled?

In C# I could just easily double click and all the code would be done for me. But in android it appears to be a bit more obscure. I thought of using the touch event handlers but then if the user has a keyboard it won't detect the change since it's not touch. I figure android should have a native event for check box state change.

Android Solutions


Solution 1 - Android

CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        if ( isChecked )
        {
            // perform logic
        }

    }
});

Solution 2 - Android

Since CheckBox (eventually) extends View, you can use a standard OnClickListener to detect when the CheckBox is actually tapped by the user (as opposed to the ListView updates):

CheckBox repeatChkBx = ( CheckBox ) findViewById( R.id.repeat_checkbox );
repeatChkBx.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
    
        if ( ((CheckBox)v).isChecked() ) {
            // perform logic
        }
    }
});

Solution 3 - Android

In Kotlin:

   checkBoxView.setOnCheckedChangeListener { _, isChecked ->
        print("checked: $isChecked")
    }

Solution 4 - Android

Try this

CheckBox checkbox=(CheckBox)findViewById(R.id.checkbox);
checkbox.setOnClickListener(new View.OnClickListener()
{
        @Override
        public void onClick(View v)
        {
            if (checkbox.isChecked())
            {
             //Perform action when you touch on checkbox and it change to selected state
            }
            else
            {
   //Perform action when you touch on checkbox and it change to unselected state
            }
        }
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnnerajbView Question on Stackoverflow
Solution 1 - AndroidCristianView Answer on Stackoverflow
Solution 2 - AndroidPhileo99View Answer on Stackoverflow
Solution 3 - AndroidMSpeedView Answer on Stackoverflow
Solution 4 - AndroidSunilView Answer on Stackoverflow