Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Development: Checkbox setChecked not working

In my xml:

<CheckBox android:id="@+id/checkboxUpdateLessonPlanAll"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/chkLessonPlanAll"
            android:onClick="onCheckboxClicked"/>

In my java:

public void onCheckboxClicked(View view) {
    //CheckBox box = (CheckBox) view;
    CheckBox box = (CheckBox) findViewById(R.id.checkboxUpdateLessonPlanAll);
    box.setChecked(!box.isChecked());
    Log.v("qwerty", "checkbox clicked " + box.isChecked() + "!!");
}

I can see my log message in LogCat and it shows it as false when I click on the checkbox but its state doesn't change. It remains unchecked.

like image 879
Rickkwa Avatar asked Nov 18 '13 05:11

Rickkwa


People also ask

How to work with CheckBox in Android?

To define the click event handler for a checkbox, add the android:onClick attribute to the <CheckBox> element in your XML layout. The value for this attribute must be the name of the method you want to call in response to a click event. The Activity hosting the layout must then implement the corresponding method.

What is setChecked in Android?

setChecked(boolean) sets the intrinsic boolean dataMember associated with your view object and setSelected(boolean) sets the UI associated with your view object.

How do you uncheck a CheckBox in Kotlin?

Just use chk1. toggle() onClick of the button to uncheck the checked ones.


2 Answers

Why would you try to overwrite the default behavior with something like the default behavior? The checkbox toggles automatically on every click.

If you want to react on that, use the OnCheckedChangeListener.

like image 184
flx Avatar answered Sep 20 '22 08:09

flx


To Make CheckBox checked or unchecked you can also use like

box.setChecked(true);

box.setChecked(false);

and to get state of CheckBox

if(box.isChecked()) {

  //do something here...

} else {

  //do something here...

}
like image 43
Ankitkumar Makwana Avatar answered Sep 19 '22 08:09

Ankitkumar Makwana