Question

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.

Was it helpful?

Solution

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

newOrSavedSwitch.setOnCheckedChangeListener(this);

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top