Using Toggle Button


A toggle button allows the user to change a setting between two states.

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

    <ToggleButton
        android:id="@+id/toggleButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ToggleButton" />

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

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

		ToggleButton tb = (ToggleButton) findViewById(R.id.toggleButton1);
		tb.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();
				}
			}
		});

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