Deux façons de gérer un Switch
Cet exemple montre deux façons de gérer un composant Switch. La première par une assignation du gestionnaire d'événement dans le code Java de l'activité. La seconde par une assignation dans le code XML du fichier de mise en page.
MainActivity.java
package net.codeandroid.grerunswitch;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
import com.google.android.material.switchmaterial.SwitchMaterial;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Switch sw1 = (Switch)findViewById(R.id.switch1);
// assignation locale du gestionnaire d'événement
sw1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
afficherMessage("ON");
} else {
afficherMessage("OFF");
}
}
});
}
// gestionnaire assigné dans le fichier XML
public void gererSwitch(View v) {
Switch sw2 = (Switch)v;
if (sw2.isChecked()) {
afficherMessage(sw2.getTextOn().toString());
} else {
afficherMessage(sw2.getTextOff().toString());
}
}
private void afficherMessage(String message) {
Toast.makeText(getApplicationContext(), "Le Swicth est " + message,
Toast.LENGTH_SHORT).show();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginLeft="30dp">
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="50px"
android:switchMinWidth="50dp"
android:textSize="25sp"
android:text="Switch 1 : "
android:checked="false"/>
<Switch
android:id="@+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="50px"
android:switchMinWidth="50dp"
android:textSize="25sp"
android:text="Switch 2 : "
android:textOff="éteint"
android:textOn="allumé"
android:onClick="gererSwitch"/>
</LinearLayout>
