Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android CheckBox how to deferentiate between user click and setChecked

I use a checkbox in my app as a button turn something on or off. But the action (load a file from the network) is done in an async task so I don't want the check to come on until the async task finishes successfully, like this

protected void onPostExecute(String result) {

            if(result==null) {
                return;
            }
            // loaded ok, turn on check mark
            MainActivity.mMp3Cb.setChecked(true);

The problem is, setChecked(true) causes OnCheckedChangeListener to fire again as if it were user input

Is there a way to avoid this? or at least detect it in onCheckedChanged?

thanks

like image 838
steveh Avatar asked Apr 04 '13 06:04

steveh


People also ask

How do I know if my checkbox is clicked Android?

So, the method to know if the check box is checked is : (CheckBox) yourCheckBox. isChecked() it returns true if the check box is checked.

What is the way to get the checked status of checkbox in Android?

You can call isChecked() on a checkbox to get its status.

How do I toggle checkbox in Android?

You can toggle the checkbox by doing this: checkbox. setChecked(! checkbox.


1 Answers

You can use the isPressed() method of the button view object. Here's an example of a toggle button in Android. buttonView.isPressed() is only true if the user clicked on the button.

@Override
public synchronized void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

    if (buttonView.isPressed()) {
        // human input  
    } else {
        // result of setChecked(boolean)
    }
}
like image 95
Florian Avatar answered Sep 25 '22 22:09

Florian