Cómo agregar un escucha a un botón de conmutación?

Im que intenta agregar a un oyente al interruptor pero por alguna razón no escucha los acontecimientos del cheque.

Implementé CompoundButton.OnCheckedChangeListener en mi actividad como esta:

 public class MyActivity extends Activity implements CompoundButton.OnCheckedChangeListener 

aquí está mi código

 @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(); } 

El brindis no se muestra, tampoco veo errores en logcat.

OnCheckedChangeListener registrar el OnCheckedChangeListener en el CompoundButton con setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener listener) :

 newOrSavedSwitch.setOnCheckedChangeListener(this); 

registro utilizando el método setOnCheckedChangeListener (this).

Puede intentar usar sólo el tipo de oyente de clase interna

  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(); } } }); 

Esto funciona muy bien para mí.

También puedes echarle un vistazo a este post Android Switch Ejemplo

  • Solicitud de switch / case con boolean
  • Cómo detectar cuándo un conmutador se desliza, no se hace clic
  • Cómo cambiar entre la cámara delantera y trasera cuando se utiliza MediaRecorder android
  • ¿Usando la cadena del recurso XML en el interruptor?
  • Botones onClick del interruptor
  • ¿Puede utilizar declaraciones condicionales en el caso de conmutación en Android?
  • Cobertura de Jacoco para la declaración de switch
  • Cómo cambiar el color de entrada del imput en xml?
  • ¿Por qué utilizar un hashmap?
  • Cómo cambiar entre actividades con viewflipper
  • Obteniendo la instancia Switch dentro de ActionBar
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.