Toggle button in Android

Today, our focus will be on the Android Toggle Button and Switch within an Android application. We will delve into the Switch button Widget and the ToggleButton widget, exploring their functionality and implementing them in our app.

Toggle button in Android

The Android Toggle Button is utilized to exhibit the on and off state on a button. Another kind of toggle button, the Switch, is primarily employed on Android devices with version 4.0 and above. The Android Switch offers a slider control. Both the ToggleButton and Switch are derived from the CompoundButton class. The XML attributes employed to define a ToggleButton are explained below.

    1. android:disabledAlpha: The level of transparency to be applied to the indicator when disabled

 

    1. android:textOff: The content displayed on the button when it is unchecked

 

    android:textOn: The content displayed on the button when it is checked

The ToggleButton is programmatically modified using the following methods.

    1. Please provide one option for paraphrasing:

 

    1. – The method getTextOff() returns the text displayed when the button is not checked.

 

    1. – The method getTextOn() returns the text displayed when the button is checked.

 

    – The method setChecked(boolean checked) allows for changing the button’s checked state.

Switch on Android

The Android Switch or SwitchCompat widget, which is a component of the AppCompat library, offers backward compatibility for Android versions older than Android API v7. It presents a customized slider for enabling or disabling functions, commonly observed in phone settings. The Android Switch Widget provides several benefits.

    1. It is the ultimate alternative for checkboxes and RadioButtons

 

      1. Implementation can be done in less than a minute

 

    Little to no requirement for drawables and other resources

Here is the provided XML layout for a SwitchCompat:

<android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Switch example"
        />

The android:text property is utilized to show a Text alongside the switch button of the slider.

Example of a Toggle Button and Switch in Android

We will show two ToggleButtons and one Switch button in this app. When the FloatingActionButton is pressed, the states of the Toggle Buttons will be shown in a SnackBar. If the action button on the SnackBar is clicked, the state of the Switch button will be changed to true. Alternatively, the state can be displayed in the SnackBar by sliding the switch.

Project Structure of Android Toggle Button and Switch

Code for an Android toggle button

In the activity_main.xml, there are no changes. The content_main.xml includes two Toggle Buttons and a Switch that are initially unchecked, according to the following code snippet.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.scdev.switchandtoggle.MainActivity"
    tools:showIn="@layout/activity_main">

    <ToggleButton
        android:id="@+id/tb1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="ToggleButton 1"
        android:textOff="Off"
        android:textOn="On" />

    <ToggleButton
        android:id="@+id/tb2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tb1"
        android:layout_alignBottom="@+id/tb1"
        android:layout_toRightOf="@+id/tb1"
        android:text="ToggleButton 2"
        android:textOff="Off"
        android:textOn="On" />

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/switchButton"
        android:layout_width="wrap_content"
        android:layout_centerInParent="true"
        android:checked="false"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Switch example"
        />


</RelativeLayout>

Below is the code for the MainActivity.java.

package com.scdev.switchandtoggle;

import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.SwitchCompat;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

    ToggleButton tb1, tb2;
    SwitchCompat switchCompat;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                StringBuilder result = new StringBuilder();
                result.append("ToggleButton1 : ").append(tb1.getText());
                result.append("\nToggleButton2 : ").append(tb2.getText());

               Snackbar snackbar= Snackbar.make(view, result.toString(), Snackbar.LENGTH_LONG)
                        .setAction("SWITCH ENABLE", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                switchCompat.setChecked(true);
                            }
                        });

                snackbar.setActionTextColor(Color.RED);
                snackbar.show();
            }
        });

        tb1= (ToggleButton)findViewById(R.id.tb1);
        tb2=(ToggleButton)findViewById(R.id.tb2);
        switchCompat=(SwitchCompat)findViewById(R.id.switchButton);

        switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                Snackbar.make(buttonView, "Switch state checked "+isChecked, Snackbar.LENGTH_LONG)
                        .setAction("ACTION",null).show();
            }
        });



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

To obtain the current status of the toggle buttons and add them to be shown in the snackbar, a StringBuilder is utilized. By implementing an OnCheckChangeListener, the subclass of Compound Button, the switch button is implemented as demonstrated in the aforementioned code. The resulting display of the application can be observed below. Thus, we conclude this tutorial on Android toggle button and switch in Android. For access to the final Android SwitchAndToggle Project, please refer to the provided link.

Please download the Android Switch and Toggle Button Project.

Source: ToggleButton Android Documentation

Paraphrased: Documentation for ToggleButton in Android API.

 

other tutorials

BroadcastReceiver Example Tutorial on Android(Opens in a new browser tab)

Tutorial on how to set up a Hibernate Tomcat JNDI DataSource.(Opens in a new browser tab)

QR code generator in Java using zxing.(Opens in a new browser tab)

Java thread ensuring Java code is thread-safe(Opens in a new browser tab)

Spring MVC HandlerInterceptorAdapter and HandlerInterceptor.(Opens in a new browser tab)

Leave a Reply 0

Your email address will not be published. Required fields are marked *