Tutorials Android How to Add Click Listener to Android Switch

How to Add Click Listener to Android Switch

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();
		}
	}
});
Total
0
Shares
guest
0 Comments
Inline Feedbacks
View all comments
Previous Post
Wordpress Tutorials

How to Notify Author with Email after Post Is Published in WordPress

Next Post

Code Snippet: Turn on and off Wi-Fi using Android API

Related Posts
By clicking “Allow All”, you agree to the storing of cookies on your device to enhance site navigation, analyze site usage, and assist in our marketing efforts. Cookie Notice
Allow All
0
Would love your thoughts, please comment.x
()
x