aBhijit aBhijit - 1 month ago 17
Android Question

How to check if android checkbox is checked within its onClick method (declared in XML)?

I have a checkbox in android which has the following xml:

<CheckBox
android:id="@+id/item_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="itemClicked" />


This is my onClick() method in my Activity class.

public void itemClicked(View v) {

//code to check if this checkbox is checked!
}


I am aware that we can create an object of the checkbox and assign id to it. But is there a better way to achieve the functionality when declaring onClick method via XML?

Answer

try this one :

public void itemClicked(View v) {
        //code to check if this checkbox is checked!
        CheckBox checkBox = (CheckBox)v;
        if(checkBox.isChecked()){

        }
    }
Comments