How to use switch widget in android application.
Switch widget is a custom On Off switch button like you have seen in android settings options to start and off WiFi, Bluetooth. So here is the complete step by step tutorial for Android Switch Button Example Tutorial to Get Switch Button On Off Value on android Example.
Android Switch Button Example Tutorial.
Code for activity_main.xml layout file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.android_examples.com.switchandroid.MainActivity" > <Switch android:id="@+id/switch1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="59dp" android:text="Switch" /> </RelativeLayout>
Code for MainActivity.java file.
package com.android_examples.com.switchandroid; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Switch; import android.widget.Toast; public class MainActivity extends Activity { Switch OnOff; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); OnOff = (Switch)findViewById(R.id.switch1); OnOff.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(OnOff.isChecked()) { Toast.makeText(MainActivity.this, "Switch is on", Toast.LENGTH_LONG).show(); } else { Toast.makeText(MainActivity.this, "Switch is Off", Toast.LENGTH_LONG).show(); } } }); } }
Screenshots: