5

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

mehdi
  • 340
  • 4
  • 17
steveh
  • 1,352
  • 2
  • 27
  • 41
  • 2
    follow this link it will resolve ur problem http://stackoverflow.com/questions/9129858/how-can-i-distinguish-whether-value-is-changed-by-user-or-programmatically-incl – steevoo Apr 04 '13 at 06:22
  • I am guessing you're executing a task each time user turns on the checkbox. At the top of my head, I'd say use a flag to differentiate between user action and the time you set the state of the checkbox. – Saeid Farivar Apr 04 '13 at 06:23
  • thanks steveoo, that worked great, now i check isPressed() at start of onCheckedChanged and if false, i know it wasn't user click. why didn't you make it an answer? – steveh Apr 04 '13 at 07:09

1 Answers1

19

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)
    }
}
mehdi
  • 340
  • 4
  • 17
Florian
  • 2,048
  • 3
  • 28
  • 36