Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect when a Switch is slided, not clicked

I managed to capture when a Switch View is clicked so the main activity responds accordingly; but whenever I slide it instead of clicking it's as if nothing has happened. How can I detect this?

like image 354
Moises Jimenez Avatar asked Aug 23 '12 08:08

Moises Jimenez


1 Answers

Having previously implemented the Switch button adding

android:onClick="onSwitchClicked"

On my .xml manifest and adding the corresponding method to my main activity did not provide desired results; since as the question says it only worked when clicked. Noticed that it is better to do it this way:

powerSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    //code
                }else{
                    //code
                }
            }
        });

This way, whenever the Switch's state changes, regardless of sliding or clicking, the method will be called.

Refer to this tutorial for further information: http://developer.android.com/guide/topics/ui/controls/togglebutton.html

like image 73
Moises Jimenez Avatar answered Nov 15 '22 17:11

Moises Jimenez