StackTips
 1 minutes

How to Add Click Listener to Android Switch

By Editorial @stacktips, On Sep 17, 2023 Android 3.11K Views

A Switch is a two-state toggle switch widget that can select between two options. Add Switch control to your Activity or Fragment layout as follows.

<Switch
        android:id="@+id/wifi_switch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:background="@android:color/background_dark"
        android:checked="false"
        android:text="Wi-Fi Settings"
        android:textColor="@android:color/white"
        android:textOff="OFF"
        android:textOn="ON" />

Now you can register switch event using setOnCheckedChangeListener(this) method.

Switch toggle = (Switch) findViewById(R.id.wifi_switch);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if (isChecked) {
			Toast.makeText(getApplicationContext(), "Switch on!", Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(getApplicationContext(), "Switch off!", Toast.LENGTH_LONG).show();
		}
	}
});
stacktips avtar

Editorial

StackTips provides programming tutorials, how-to guides and code snippets on different programming languages.