Tutorial

Android ActionBar Example Tutorial

Published on August 3, 2022
author

Anupam Chugh

Android ActionBar Example Tutorial

Today we will look into Android ActionBar. Action Bar is one of the important part of any application, whether it’s a web application or a mobile app. Today we will learn how to implement action bar in android apps using ActionBar component.

Android ActionBar

android actionbar, android action bar Android ActionBar is a menu bar that runs across the top of the activity screen in android. Android ActionBar can contain menu items which become visible when the user clicks the “menu” button. In general an ActionBar consists of the following four components:

  • App Icon: App branding logo or icon will be displayed here
  • View Control: A dedicated space to display Application title. Also provides option to switch between views by adding spinner or tabbed navigation
  • Action Buttons: Some important actions of the app can be added here
  • Action Overflow: All unimportant action will be shown as a menu

Android ActionBar Setting Up

All activities that use the theme Theme.Holo or a theme derived from Theme.Holo will automatically contain an ActionBar.

Android ActionBar Menu

The simplest way to get toolbar icons and action overflow items into the action bar is by creating menu XML resource file found in res/menu folder. We can add menu items in the raw xml file present in the folder as follows: menu_main.xml

<menu 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" tools:context=".MainActivity">
    
    <item
        android:id="@+id/add" android:icon="@android:drawable/ic_menu_add" app:showAsAction="always"   android:title="@string/add"/>
    <item
        android:id="@+id/reset" android:icon="@android:drawable/ic_menu_revert" app:showAsAction="always|withText" android:title="@string/reset"/>
    <item
        android:id="@+id/about" android:icon="@android:drawable/ic_dialog_info" app:showAsAction="never" android:title="@string/about">
    </item>
    <item
        android:id="@+id/exit"  app:showAsAction="never" android:title="@string/exit">
    </item>
</menu>

There are four things that are needed to be configured for every menu item.

  1. android:id: attribute specifies the id of the menu item. This works like ids anywhere else in the Android app. An android:id value starting with a @+id/ will create a constant in the R.menu constant collection
  2. android:title: attribute value contains the title of the menu item
  3. android:icon: attribute references an icon in the drawable directories
  4. android:showAsAction: This attribute indicates how the given item should be portrayed in the action bar. We can choose from any of the flags mentioned below:
    • always to keep it in the ActionBar at all times
    • ifRoom to keep it only if space is available
    • never this means that the menu item will not be placed in the ActionBar as an icon. It will only be visible when the menu button is clicked, in the menu that’s popping up
    • |withText : we can append this to either always or ifRoom, to indicate that the toolbar button to be both the icon and the title, not just the icon

Note that always is not guaranteed to be a toolbar button - if you ask for 100 always items, you will not have room for all of them. However, always items get priority for space in the action bar over ifRoom items.

Inflating the Menu Into the Android ActionBar

In order for the menu items defined in the menu XML file to be displayed, you need to inflate the menu file. We do so inside the onCreateOptionsMenu() method of the activity where we wish to add the ActionBar. Here is the code snippet:

@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;
}

The R.menu.menu_main parameter is the constant referring to the menu XML file. The menu parameter is the menu into which we want to inflate the menu items.

Responding to Android Action Bar Events

To find out when the user taps on one of these things, we’ll need to override onOptionsItemSelected() from the MainActivity as shown below:

@Override
public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) {
    case R.id.add:
        //add the function to perform here
        return(true);
    case R.id.reset:
        //add the function to perform here
        return(true);
    case R.id.about:
        //add the function to perform here
        return(true);
    case R.id.exit:
        //add the function to perform here
        return(true);
}
    return(super.onOptionsItemSelected(item));
}

Now let’s assign some basic functions to each menu items in our project.

Project Structure

android action bar example, android actionbar project, android actionbar

Android ActionBar Example Code

We’ve implemented the four menu items in the MainActivity as shown in the snippet below: MainActivity.java

package com.journaldev.actionbar;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView count;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @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) { switch(item.getItemId()) {
        case R.id.add:
            count=(TextView)findViewById(R.id.textView);
            count.setText("Add is clicked");
            return(true);
        case R.id.reset:
            count=(TextView)findViewById(R.id.textView);
            count.setText("Nothing is selected");
            return(true);
        case R.id.about:
            Toast.makeText(this, R.string.about_toast, Toast.LENGTH_LONG).show();
            return(true);
        case R.id.exit:
            finish();
            return(true);

    }
        return(super.onOptionsItemSelected(item));
    }
}

The items are assigned their respective functions. The item selected is determined from its id that was defined in the menu_main.xml file. Here we just change the TextView contents in the first two items, display a toast in the third and exit the application in the fourth item. Note that the AppCompatActivity is a replacement for the deprecated version of ActionBarActivity. The styles.xml file is defined as follows:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

</resources>

As you can see the parent theme uses a derivative of Theme.AppCompat which holds an ActionBar by default(unless you use Theme.AppCompat.Light.NoActionBar class). Hence there is no need to define it explicitly here.

Android Action Bar Backporting

  1. Since ActionBar was introduced after Android Honeycomb 3.0, to implement ActionBar when minSdkVersion is 11 or less we need to import the app-compat-v7 jar into our gradle as we have done here to enable backward compatibility
  2. Another way is to import and extend the MainActivity with ActionBarSherlock independent of the action bar backport, since this class was introduced after Android 3.0

Below image shows the output produced by our project, you can see that the ActionBar includes the predefined icons. The textview updates the content since add icon was clicked. The textview reverts the content to the original since reset was clicked. When about is clicked, toast notification appears as shown below. android actionbar example This brings an end to android action bar example tutorial. You should also read about android custom ActionBar. You can download android ActionBar project from below link.

Download Android ActionBar Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Anupam Chugh

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
October 12, 2018

Thank you very for the tutorial please can show me how to customize the toolbar so that it shows the name of the open page on the title bar

- Netmat Gumes

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    October 6, 2018

    Hai Iam Rizwan How to Set Title center in Tool bar toolbar=(Toolbar)findViewById(R.id.toolbar); toolbar.setTitle(getResources().getString(R.string.setTitle)); toolbar.setTitleTextColor(getResources().getColor(R.color.title)); TextView customTitle=toolbar.findViewById(R.id.setTitleText); setSupportActionBar(toolbar);

    - rizwan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      April 17, 2018

      how to change color of the text in actionbar??

      - Pranjul Dhiman

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        June 16, 2017

        Actionbar is depreciated and dead, avoid using actionbar and start using toolbar, it will be good it this tutorial can be updated to use toolbar and use it as actionbar.

        - satish kadyan

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          June 14, 2017

          I did everything as it is in the Tut’ but when I run the app, nothing appears except for the textview “Nothing is selected”

          - Les Mok

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            February 10, 2017

            It is really very interesting and very clear.But,how could I make it floating that toast?

            - petros

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              January 12, 2017

              keep getting: count=(TextView)findViewById(R.id.textView); with textView red, - can resolve symbol and Toast.makeText(this, R.string.about_toast, Toast.LENGTH_LONG).show(); same for about_toast very much a newbie, probably a easy answer, I hope? !

              - gary

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                January 2, 2017

                If I want to add a back button before the App title, then what should I have to do?

                - Shinoy Shaji

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 24, 2016

                  How to add animation in menu bar like Inshorts app ?

                  - Sidhartha

                    Try DigitalOcean for free

                    Click below to sign up and get $200 of credit to try our products over 60 days!

                    Sign up

                    Join the Tech Talk
                    Success! Thank you! Please check your email for further details.

                    Please complete your information!

                    Featured on Community

                    Get our biweekly newsletter

                    Sign up for Infrastructure as a Newsletter.

                    Hollie's Hub for Good

                    Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                    Become a contributor

                    Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                    Welcome to the developer cloud

                    DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                    Learn more