Le Tutoriel de Android Switch
View more Tutorials:
Sous Android, Switch est un contrôle d'interface utilisateur (user interface control) avec deux états ON/OFF. Bien que ses fonctions ressemblent beaucoup à CheckBox et ToggleButton, leurs interfaces sont différents.


Switch ressemble beaucoup à CheckBox et ToggleButton en termes de fonction et de mode d'utilisation. Tous les trois sont sous-classes de CompoundButton qui se différencient au niveau de leur interface.

Image (Icon)
Switch est une sous-classe de Button qui permet d'afficher au maximum quatre icônes dans les quatre bords en utilisant les attributs android:drawableLeft, android:drawableTop, android:drawableRight, android:drawableBottom, android:drawableStart, android:drawableEnd.

<Switch android:id="@+id/switch13" android:drawableLeft="@drawable/icon_bus" android:drawableTop="@drawable/icon_car" android:drawableBottom="@drawable/icon_boat" android:text="Switch" ... />
android:gravity
L'attribut android:gravity est utilisé pour définir la position d'affichage du texte d'un Switch. Sa valeur est une combinaison des valeurs suivantes:
Constant in Java | Value | Description |
Gravity.LEFT | left | |
Gravity.CENTER_HORIZONTAL | center_horizontal | |
Gravity.RIGHT | right | |
Gravity.TOP | top | |
Gravity.CENTER_VERTICAL | center_vertical | |
Gravity.BOTTOM | bottom | |
Gravity.START | start | |
Gravity.END | end | |
Gravity.CENTER | center | |

<Switch android:id="@+id/switch13" android:text="Switch" android:gravity="bottom|center" ... />
android:switchPadding

L'attribut android:switchPaddiing permet d'installer un espace entre le track et le text de Switch.
<Switch android:id="@+id/switch1" android:drawableLeft="@drawable/icon_alarm" android:switchPadding="10dp" android:text="Alarm" ... />
android:layoutDirection = "rtl"
L'attribut android:layoutDirection est assisté à partir d Android 4.2 (API Level 17) qui permet de définir la direction de la disposition (Layout direction) d'un View. Par défaut, la valeur de cet attribut est "ltr" (Left to Right).
Afin d'utiliser l'attribut android:layoutDirection, ili faut ouvrir le fichier build.gradle (Module: app) et modifier la valeur de minSdkVersion, et s'assurer que sa nouvelle valeur est égale ou supérieure à 17.


<!-- Layout Direction Default: Left to Right --> <Switch android:id="@+id/switch41" android:switchPadding="5dp" android:text="Alarm" ... /> <!-- Layout Direction: Right to Left --> <Switch android:id="@+id/switch42" android:layoutDirection="rtl" android:switchPadding="5dp" android:text="Alarm" ... />
textOn/textOff
Android 5.0 (API Level 21) permet d'afficher textOn/textOff correspondant aux états ON/OFF de Switch.

<!-- textOn/textOff = ON/OFF (Default) --> <Switch android:id="@+id/switch51" android:text="Alarm" android:showText="true" ... /> <!-- textOn/textOff = Enabled/Disabled --> <Switch android:id="@+id/switch52" android:text="Alarm" android:showText="true" android:textOff="Disabled" android:textOn="Enabled" ... />
toggle()
ToggleButton, CheckBox, RadioButton, Switch sont toutes des sous-classes de CompoundButton. Elles héritent donc de la méthode toggle(). C'est la méthode la plus utilisée pour changer leur état de ON (Checked) à OFF (Unchecked) et inversement.
CompoundButton button = (Switch) findViewById(R.id.switch); button.toggle();
L'attribut style est une option de Switch qui permet de définir le style pour Switch. Vous pouvez utiliser certains styles disponibles dans la bibliothèque d'Android.

Remarque: Actuellement, le nombre de style(s) disponible dans la bibliothèque sont limités et ils ne sont pas vraiement différents des styles par défaut. Il s'agit effectivement d'un point assez décevant.

Switch Styles Example
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView61" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="TextAppearance.AppCompat.Widget.Switch" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <Switch android:id="@+id/switch61" style="@style/TextAppearance.AppCompat.Widget.Switch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:showText="false" android:text="Alarm" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView61" /> <TextView android:id="@+id/textView62" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="Widget.AppCompat.CompoundButton.Switch" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/switch61" /> <Switch android:id="@+id/switch62" style="@style/Widget.AppCompat.CompoundButton.Switch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:showText="false" android:text="Alarm" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView62" /> <TextView android:id="@+id/textView63" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="Widget.Material.CompoundButton.Switch" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/switch62" /> <Switch android:id="@+id/switch63" style="@android:style/Widget.Material.CompoundButton.Switch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:showText="false" android:text="Alarm" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView63" /> <TextView android:id="@+id/textView64" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="16dp" android:layout_marginEnd="16dp" android:text="Widget.Material.Light.CompoundButton.Switch" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/switch63" /> <Switch android:id="@+id/switch64" style="@android:style/Widget.Material.Light.CompoundButton.Switch" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="16dp" android:layout_marginTop="8dp" android:showText="false" android:text="Alarm" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/textView64" /> </androidx.constraintlayout.widget.ConstraintLayout>
Il existe beaucoup d'évènements relatifs à un Switch, et les deux ci-dessous sont les plus utilisés:
- setOnClickListener(View.OnClickListener)
- setOnCheckedChangeListener(CompoundButton.OnCheckedChangeListener)
On Click Event:
L'évènement se produit quand l'utilisateur clique (click) sur Switch. Cela donne le même effet que quand l'utilisateur clique sur un Button.
Switch switch1 = (Switch) findViewById(R.id.switch1); switch1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { boolean checked = ((Switch) v).isChecked(); if (checked){ // Your code } else{ // Your code } } });
On Checked Change Event:
L'évènement se produit quand Switch change d'état en raison d'une action de l'utilisateur ou sous l'effet de la méthode setChecked(newState), etc.
Switch switch1 = (ToggleButton) findViewById(R.id.switch1); switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked) { // Your code } else { // Your code } } });