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

aBhijit picture aBhijit · Aug 20, 2013 · Viewed 159.4k times · Source

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

Anand picture Anand · Aug 20, 2013

try this one :

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

  }
}