Using Switch Controls


A Switch is a two-state toggle switch widget that can select between two options. Its similiar to Wireless on/off method.

For adding a Switch to your layout file (res/layout/*.xml)

    <Switch
        android:id="@+id/switch1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Switch" />

For adding the functionality part of the Switch, copy and paste the below code in your onCreate() function of JAVA File.

Note: Below the SetContentView() line in onCreate() function.

		Switch sw = (Switch) findViewById(R.id.switch1);
		sw.setOnCheckedChangeListener(new OnCheckedChangeListener() {

			@Override
			public void onCheckedChanged(CompoundButton buttonView,
					boolean isChecked) {
				// TODO Auto-generated method stub
				if (isChecked) {
					Toast.makeText(MainActivity.this, "true",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(MainActivity.this, "false",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

Note: Make sure you change the minSdkVersion to 14 in AndroidManifest.xml file.

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="18" />

Save the changes and run your Android Application in Emulator or an Android Device. Post your comments.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s