2012-06-30 12 views
129

Me gustaría implementar un botón de cambio, android.widget.Switch (disponible desde API v.14).android.widget.Switch - on/off event listener?

<Switch 
    android:id="@+id/switch1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="Switch" /> 

Pero no estoy seguro de cómo agregar un detector de eventos para el botón. ¿Debería ser un oyente "onclick"? ¿Y cómo sabría si está activado o no?

+3

OnClick via XML realmente funciona, pero solo para "clics" en el botón, no para "diapositivas". – m02ph3u5

Respuesta

290

Interruptor hereda CompoundButton atributos 's, por lo que recomiendo el OnCheckedChangeListener

mySwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     // do something, the isChecked will be 
     // true if the switch is in the On position 
    } 
}); 
+0

Funciona como un amuleto, gracias Sam – Johan

+1

@Johan No hay problema. No sé ustedes, pero me gustaría que lo llamaran OnCheckChangedListener, similar a OnItemSelectedListener, ya que On-_Noun _-_ Verb_-Listener es una convención de nombres establecida. – Sam

+5

No funciona cuando presiona prolongadamente el botón, luego lo desliza/lo cambia. –

29

Utilice el siguiente fragmento de añadir un interruptor a su disposición a través de XML:

<Switch 
    android:id="@+id/on_off_switch" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:textOff="OFF" 
    android:textOn="ON"/> 

Luego, en su onCreate de Actividad método, obtener una referencia a su Switch y establecer su OnCheckedChangeListener:

Switch onOffSwitch = (Switch) findViewById(R.id.on_off_switch); 
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 

@Override 
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
    Log.v("Switch State=", ""+isChecked); 
}  

}); 
+3

Esta es una respuesta más clara que le da el diseño y el código detrás para que coincida. – AshesToAshes

+0

cómo administrar múltiples switchcompat en el único oyente? Sugerir respuesta para eso –

16

definir su diseño XML:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.neoecosystem.samplex.SwitchActivity"> 

    <Switch 
     android:id="@+id/myswitch" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" /> 

</RelativeLayout> 

A continuación, crear una actividad

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener { 

    Switch mySwitch = null; 


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


     mySwitch = (Switch) findViewById(R.id.myswitch); 
     mySwitch.setOnCheckedChangeListener(this); 
    } 

    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      // do something when check is selected 
     } else { 
      //do something when unchecked 
     } 
    } 

    **** 
} 

======== Por continuación API 14 uso SwitchCompat =========

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:tools="http://schemas.android.com/tools" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context="com.neoecosystem.samplex.SwitchActivity"> 

    <android.support.v7.widget.SwitchCompat 
     android:id="@+id/myswitch" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" /> 

</RelativeLayout> 

Actividad

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener { 

    SwitchCompat mySwitch = null; 


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


     mySwitch = (SwitchCompat) findViewById(R.id.myswitch); 
     mySwitch.setOnCheckedChangeListener(this); 
    } 

    @Override 
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
     if (isChecked) { 
      // do something when checked is selected 
     } else { 
      //do something when unchecked 
     } 
    } 
    ***** 
} 
+2

no olvide marcar buttonView.isPressed() – JacksOnF1re

4

El diseño del widget Switch es algo como esto.

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:orientation="vertical"> 
    <Switch 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_marginRight="20dp" 
     android:gravity="right" 
     android:text="All" 
     android:textStyle="bold" 
     android:textColor="@color/black" 
     android:textSize="20dp" 
     android:id="@+id/list_toggle" /> 
</LinearLayout> 

En la clase Actividad, puede codificar de dos maneras. Depende del uso que puedas codificar.

primera forma

public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener { 
Switch list_toggle; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.return_vehicle); 

    list_toggle=(Switch)findViewById(R.id.list_toggle); 
    list_toggle.setOnCheckedChangeListener(this); 
    } 
} 

public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) { 
    if(isChecked) { 
     list_toggle.setText("Only Today's"); //To change the text near to switch 
     Log.d("You are :", "Checked"); 
    } 
    else { 
     list_toggle.setText("All List"); //To change the text near to switch 
     Log.d("You are :", " Not Checked"); 
    } 
} 

La segunda manera

public class ActivityClass extends Activity { 
Switch list_toggle; 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.return_vehicle); 

    list_toggle=(Switch)findViewById(R.id.list_toggle); 
    list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      if(isChecked) { 
      list_toggle.setText("Only Today's"); //To change the text near to switch 
      Log.d("You are :", "Checked"); 
      } 
      else { 
      list_toggle.setText("All List"); //To change the text near to switch 
      Log.d("You are :", " Not Checked"); 
      } 
     }  
    }); 
    } 
} 
0

Para aquellos que utilizan Kotlin, puede configurar un detector para un interruptor (en este caso tiene el ID de mySwitch) de la siguiente manera:

mySwitch.setOnCheckedChangeListener { _, isChecked -> run { 
     // do whatever you need to do when the switch is toggled here 
    } 
} 

isChecked es verdadero si el interruptor está actualmente marcado (ON) y falso otherw Ise.