Skip to content
Related Articles

Related Articles

Improve Article

How to Add Switch in Android ActionBar?

  • Last Updated : 26 May, 2021

In Android, Switch is a two-state toggle switch widget that is used to select a choice between two options. It is generally an on/off button that indicates the current state of the switch. Normal Basic Features for which switch can be used in ActionBar of application:

  • To switch to the dark mode or light mode in the application.
  • To activate or inactivate the services of the application.
  • To on/off Bluetooth or media-related features etc.

Now let us see the step-by-step implementation to do so.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Go to “res” and create a new directory and name it as “menu”



Refer to this Create Menu Folder & Menu File in Android Studio article and create a new Menu resource file and name it as “action_menu“. Also, go to layout and create a new layout resource file and name it as “use_switch“.

Step 3: Open the action_menu.xml file and use the following code in it

XML




<?xml version="1.0" encoding="utf-8"?>
    <item
        android:id="@+id/switch_action_bar"
        android:title="Switch"
        app:actionLayout="@layout/use_switch"
        app:showAsAction="always" />
</menu>

Step 4: Open the use_switch.xml file and use the following code in it

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
  
    <Switch
        android:id="@+id/switch2"
        android:layout_width="63dp"
        android:layout_height="58dp"
        android:padding="6dp"
        android:scaleX="1.3"
        android:scaleY="1.3"
        android:switchMinWidth="40dp"
        android:textSize="8sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.001" />
      
</androidx.constraintlayout.widget.ConstraintLayout>

Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 



XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!-- you can use any image according to you -->
    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.434"
        app:srcCompat="@drawable/gfgimage" />
  
    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.918"
        app:srcCompat="@drawable/gfgimage" />
      
</androidx.constraintlayout.widget.ConstraintLayout>

Step 6: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. 

Java




import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
public class MainActivity extends AppCompatActivity {
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
  
    }
  
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.action_menu, menu);
        MenuItem itemswitch = menu.findItem(R.id.switch_action_bar);
        itemswitch.setActionView(R.layout.use_switch);
          
        final Switch sw = (Switch) menu.findItem(R.id.switch_action_bar).getActionView().findViewById(R.id.switch2);
         
        sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    Toast.makeText(MainActivity.this, "Switch is working", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return true;
    }
}

Output:

Hence we developed an application where we can use the switch in the action bar of the application to implement basic features of an app. The same process can be applied in any other application to add a switch in ActionBar and can be used to implement any feature according to the need of the application. 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :