Search code examples
javaandroidswitch-statementoncheckedchanged

How to add a listenner to a Switch Button?


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.


Solution

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

    newOrSavedSwitch.setOnCheckedChangeListener(this);