Search code examples
androidandroid-switchoncheckedchanged

Switch setOnCheckedChangeListener not working properly


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.


Solution

  • Use compoundButton.isChecked instead of isSelected.