Jeremy G
Jeremy G

Reputation: 43

Toggle checked state of checkbox when clicked

I'm playing around with my first Android app - it's a simple calculator that works out the total cost of an item based on it's final sale price and any other additional fees. One of these fees is tax which is not always applicable to all items, therefore I've added a checkbox to specify whether VAT is applicable or not when calculating the cost.

I've created a method in the java to toggle the checked state of the checkbox and bound it to the onClick event of the checkbox, however nothing happens when I press the checkbox.

Here's the java code:

public void changeCheckedState(View view) {
    CheckBox checkBox = (CheckBox)findViewById(R.id.cbIncludeVAT);

    checkBox.setChecked(!checkBox.isSelected());
}

Here's the xml for the checkbox view:

<CheckBox
    android:id="@+id/cbIncludeVAT"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="8dp"
    android:layout_marginTop="26dp"
    android:checked="true"
    android:onClick="changeCheckedState"
    android:text="Include VAT?"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/lblCardFee" />

I'm running/testing the app on my Android phone and have been unable to get debugging to work so I have no idea if the event handler is even firing when I press the checkbox.

I have searched SO for a solution and tries various fixes but nothing seems to work - the check box simply remains checked (it's default/starting state).

Upvotes: 2

Views: 1860

Answers (1)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

he check box simply remains checked (it's default/starting state).

When your click on checkbox checkBox.isSelected() gives you true and ! will flip it to false hence checkbox will always be set to false mean unchecked.

                     checkBox.isSelected()   // true when your click
checkBox.setChecked(!checkBox.isSelected()); // ! will convert it to false
// so checkbox will always be set to unchecked by this code  

Note : you need not to set the checkbox state

public void changeCheckedState(View view) {
    CheckBox checkBox = (CheckBox)findViewById(R.id.cbIncludeVAT);
    // ^^^^ declare it outside  
   //  initialize checkBox inside oncreate rather than doing on every click 

   if(checkBox.isSelected()){
       // box is checked 
    }else{
       // box is unchecked 
    }
}

Upvotes: 2

Related Questions