Switch
Layout
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/my_switch"
android:text="turn on or off"
android:onClick="onSwitchClick" android:layout_margin="8dp
Java
public void onSwitchClick(View view) {
Switch aSwitch = findViewById(R.id.my_switch);
aSwitch.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
StringBuffer onOff = new StringBuffer().append("On or off? ");
if (isChecked) { // The switch is enabled
onOff.append("ON ");
} else { // The switch is disabled
onOff.append("OFF ");
}
Toast.makeText(getApplicationContext(), onOff.toString(),
Toast.LENGTH_SHORT).show();
}
});
}
Last updated