Switch setOnCheckedChangeListener not working properly

5.7k views Asked by At

I have a Switch named aSwitch. I have the following code in my setOnCheckedChangeListener :

    aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (!compoundButton.isSelected()) {
                Log.i("Yeah" , "Is Not Selected");
                invertLock(-1);
            }
            else {
                if (Utilities.isLockEnabled(context)) {
                    Log.i("Yeah" , "Is Locked");
                    Utilities.showLockEnabled(context);
                }
                else {
                    Log.i("Yeah" , "Is Not Locked");
                    invertLock(1);
                }
            }
        }
    });

The first state of the Switch is always selected=false. When I click on the switch, it gets selected=true and my Logcat shows

I/Yeah: Is Not Selected

Then when the switch is selected=true, and then turned off, my Logcat once again shows

I/Yeah: Is Not Selected

Is there any problem in my code? Please help me out.

Thanks.

2

There are 2 answers

1
fweigl On BEST ANSWER

Use compoundButton.isChecked instead of isSelected.

1
Anurag Meena On

Try this code

aSwitch.setOnCheckedChangeListener(new 
    CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if (!b) {
            Log.i("Yeah" , "Is Not Selected");
            invertLock(-1);
        }
        else {
            if (Utilities.isLockEnabled(context)) {
                Log.i("Yeah" , "Is Locked");
                Utilities.showLockEnabled(context);
            }
            else {
                Log.i("Yeah" , "Is Not Locked");
                invertLock(1);
            }
        }
    }
});