How to add a listenner to a Switch Button?

460 views Asked by At

Im trying to add a listenner to Switch but for some reason it does not listen to the check events.

I implemented CompoundButton.OnCheckedChangeListener on my activity like this:

public class MyActivity extends Activity 
           implements CompoundButton.OnCheckedChangeListener 

here is my code

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_layout);

    newOrSavedSwitch = (Switch)  findViewById(R.id.new_or_saved_switch);        
}

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
   Toast.makeText(this, "Monitored switch is " + (isChecked ? "on" : "off"),
           Toast.LENGTH_SHORT).show();
}

The toast does not show, also I dont see errors in logcat.

2

There are 2 answers

0
Ahmad On BEST ANSWER

You have to register the OnCheckedChangeListener onto the CompoundButton with setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener):

newOrSavedSwitch.setOnCheckedChangeListener(this);
1
Nilanchala On

register switch using setOnCheckedChangeListener(this) method.

You may try just using inner class type listener

 toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {                   
                    Toast.makeText(getApplicationContext(), "Wi-Fi Enabled!", Toast.LENGTH_LONG).show();
                } else {                   
                    Toast.makeText(getApplicationContext(), "Wi-Fi Disabled!", Toast.LENGTH_LONG).show();
                }
            }
        });

This works great for me.

You may also like to have an look at this post Android Switch Example