How to Add Click Listener to Android Switch

LinkedIn
Hacker News

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();
		}
	}
});

-Advertisement-

Tagged in : Android Java

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.