The Wayback Machine - https://web.archive.org/web/20240926125506/https://www.geeksforgeeks.org/actionbar-in-android-with-example/
Open In App

ActionBar in Android with Example

Last Updated : 05 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Android applications, ActionBar is the element present at the top of the activity screen. It is a salient feature of a mobile application that has a consistent presence over all its activities. It provides a visual structure to the app and contains some of the frequently used elements for the users. Android ActionBar was launched by Google in 2013 with the release of Android 3.0(API 11). Before that, the name of this top most visual element was AppBar. AppBar contains only the name of the application or current activity. It was not very much useful for the users and developers also have negligible option to customize it. 

Google announced a support library along with the introduction of ActionBar. This library is a part of AppCompat and its purpose is to provide backward compatibility for older versions of Android and to support tabbed interfaces. All applications that use the default theme provided by the Android(Theme.AppCompat.Light.DarkActionBar), contains an ActionBar by default. However, developers can customize it in several ways depending upon their needs. Components included in the ActionBar are:

  • App Icon: Display the branding logo/icon of the application.
  • View Controls: Section that displays the name of the application or current activity. Developers can also include spinner or tabbed navigation for switching between views.
  • Action Button: Contains some important actions/elements of the app that may be required to the users frequently.
  • Action Overflow: Include other actions that will be displayed as a menu.

Designing a Custom ActionBar

The following example demonstrates the steps involved in creating a custom ActionBar for the MainActivity of an application. All important aspects of visual elements like icon, title, subtitle, action buttons, and overflow menu will be covered. 

Note: Following steps are performed on Android Studio version 4.0

Step 1: Default ActionBar

As mentioned earlier, every android app contains an ActionBar by default. This pre-included ActionBar display title for the current activity that is managed by the AncdroidManifest.xml file. The string value of the application’s title is provided by @string/app_name resource present under the application nodes.

<application

       …..

      …..

       android:label=”@string/app_name”

     …..

</application>

Output:

Step 2: Creating a new directory and design items of ActionBar

To code the elements of ActionBar, create a new directory in the resource folder of the application project files. Right-click on the res folder and selects New -> Directory. Give the name “menu” to the new directory. 

Further, create a new Menu Resource File by right click on the menu directory. As the ActionBar is being created for the main Activity, type the name as “main” to the Menu Resource File. With this, a new file named “main.xml” must be created under the menu directory. In this file, one can declare the items which will be displayed as the action buttons of the ActionBar.

For every menu items, the following attributes are needed to be configured:

  • android:title: Its value contains the title of the menu item that will be displayed when a user clicks and holds that item in the app.
  • android:id: A unique ID for the menu item that will be used to access it anywhere in the whole application files.
  • android:orderInCategory: The value of this attribute specify the item’s position in the ActionBar. There are two ways to define the position of different menu items. The first one is to provide the same value of this attribute for all items and the position will be defined in the same order as they are declared in the code. The second way is to provide a different numeric value for all items and then the items will position themselves according to ascending order of this attribute’s value.
  • app:showAsAction: This attribute defines how the item is going to be present in the action bar. There are four possible flags to choose from:
    • a. always: To display the item in the ActionBar all the time.
    • b. ifRoom: To keep the item if space is available.
    • c. never: With this flag, the item will be not be displayed as an icon in ActionBar, but will be present in the overflow menu.
    • d. withText: To represent an item as both icon and the title, one can append this flag with the always or ifRoom flag(always|withText or ifRoom|withText).
  • android:icon: The icon of an item is referenced in the drawable directories through this attribute.

Icon of an ActionBar Item

In order to provide an icon to an item, right-click on the res folder, select new, and then Image Asset. A dialog box will appear, choose the Icon Type as Action Bar and Tab Icons. Choose assets type as “Clip Art” and select an image from the clip art collection. Provide a desired name to the icon. Click on Next, then Finish. This icon will now get loaded in the drawable directory of the res folder. The name provided by the developers to these icons will now be used to reference the item’s icon resource.

Below is the code to place a search icon, refresh icon, and an overflow menu in the ActionBar.

XML




<?xml version="1.0" encoding="utf-8"?>
 
    <!-- action button for search -->
    <item android:title="search"
        android:id="@+id/search"
        android:orderInCategory="100"
        app:showAsAction="ifRoom"
        android:icon="@drawable/search_icon"/>
 
    <!-- action button for refresh -->
    <item android:title="refresh"
        android:id="@+id/refresh"
        android:orderInCategory="100"
        app:showAsAction="ifRoom"
        android:icon="@drawable/refresh_icon"/>
 
    <!-- action button for copy -->
    <item android:title="copy"
        android:id="@+id/copy"
        android:orderInCategory="100"
        app:showAsAction="never"
        android:icon="@drawable/copy_icon"/>
</menu>


Output:

Step 3: Working with the Activity File

The items of an ActionBar is designed with a purpose to perform some operations. Those operations/actions of the items are declared in that Activity file for which the ActionBar has been designed. In this example, the target activity is the MainActivity file. Further, the custom title, subtitle, and application logo are also defined in this file. Below is the proper code to design all mentioned items and to display a toast message when a user clicks on the items of ActionBar.

Java




import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate( Bundle savedInstanceState ) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        // calling this activity's function to
        // use ActionBar utility methods
        ActionBar actionBar = getSupportActionBar();
 
        // providing title for the ActionBar
        actionBar.setTitle("  GfG | Action Bar");
 
        // providing subtitle for the ActionBar
        actionBar.setSubtitle("   Design a custom Action Bar");
 
        // adding icon in the ActionBar
        actionBar.setIcon(R.drawable.app_logo);
 
        // methods to display the icon in the ActionBar
        actionBar.setDisplayUseLogoEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
 
    }
 
    // method to inflate the options menu when
    // the user opens the menu for the first time
    @Override
    public boolean onCreateOptionsMenu( Menu menu ) {
 
        getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
 
    // methods to control the operations that will
    // happen when user clicks on the action buttons
    @Override
    public boolean onOptionsItemSelected( @NonNull MenuItem item ) {
 
        switch (item.getItemId()){
            case R.id.search:
                Toast.makeText(this, "Search Clicked", Toast.LENGTH_SHORT).show();
                break;
            case R.id.refresh:
                Toast.makeText(this, "Refresh Clicked", Toast.LENGTH_SHORT).show();
                break;
            case R.id.copy:
                Toast.makeText(this, "Copy Clicked", Toast.LENGTH_SHORT).show();
                break;
        }
        return super.onOptionsItemSelected(item);
    }
}


Kotlin




import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
 
        // calling this activity's function to
        // use ActionBar utility methods
        val actionBar = supportActionBar
 
        // providing title for the ActionBar
        actionBar!!.title = "  GfG | Action Bar"
 
        // providing subtitle for the ActionBar
        actionBar.subtitle = "   Design a custom Action Bar"
 
        // adding icon in the ActionBar
        actionBar.setIcon(R.drawable.app_logo)
 
        // methods to display the icon in the ActionBar
        actionBar.setDisplayUseLogoEnabled(true)
        actionBar.setDisplayShowHomeEnabled(true)
    }
 
    // method to inflate the options menu when
    // the user opens the menu for the first time
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.main, menu)
        return super.onCreateOptionsMenu(menu)
    }
 
    // methods to control the operations that will
    // happen when user clicks on the action buttons
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        when (item.itemId) {
            R.id.search -> Toast.makeText(this, "Search Clicked", Toast.LENGTH_SHORT).show()
            R.id.refresh -> Toast.makeText(this, "Refresh Clicked", Toast.LENGTH_SHORT).show()
            R.id.copy -> Toast.makeText(this, "Copy Clicked", Toast.LENGTH_SHORT).show()
        }
        return super.onOptionsItemSelected(item)
    }
}


Output:

Step 4: Color of the ActionBar

Head over to style.xml file located in the values directory of the res folder. To change the default color of the ActionBar, one has to change the colorPrimary resource. Below is the code to make the ActionBar color ‘green’.

XML




<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
     
    <!-- provided green color to the ActionBar -->
    <item name="colorPrimary">#0F9D58</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>
 
</resources>


Output:

Step 5: Working with activity_main.xml file

This file defines the layout of the activity. In this example, the prime focus is on ActionBar, thus the activity will contain only a simple TextView. Below is the code.

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"
    android:background="#168BC34A"
    tools:context=".MainActivity">
 
    <!-- Adding a TextView in the activity -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Geek!!"
        android:textColor="#000000"
        android:textSize="24sp"
        android:textStyle="bold"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
   
  </androidx.constraintlayout.widget.ConstraintLayout>


       

Output:

Advantages of ActionBar

  • Provides a customized area to design the identity of an app
  • Specify the location of the user in the app by displaying the title of the current Activity.
  • Provides access to important and frequently used actions
  • Support tabs and a drop-down list for view switching and navigation.

Disadvantages of ActionBar

  • All features of the ActionaBar are not introduced at once but were introduced with the release of different API levels such as API 15, 17, and 19.
  • The ActionBar behaves differently when it runs on different API levels.
  • The features that were introduced with a particular API does not provide backward compatibility.

Note: To resolve all the problems related to ActionBar, Google introduced ToolBar along with the release of API 21(Android Lollipop).



Previous Article
Next Article

Similar Reads

How to Add a Custom View Inside ActionBar in Android?
In Android, an Action Bar, or an app bar is a dedicated space at the top of the application on the screen that indicates the name of the application or activity. An Action bar helps users navigate or locate themself in the application. A sample Action Bar is shown in the below image. In this article, we will show you how you could customize the Act
3 min read
Different Ways to Hide ActionBar in Android with Examples
ActionBar is a primary toolbar within the activity that may display the activity title, application-level navigation affordances, and other interactive items. Although Action Bar is an important feature for android applications, sometimes we have the need to hide it in either the entire app, some particular activity, or during some particular work.
4 min read
Difference Between ActionBar and Toolbar in Android
ActionBar ActionBar is the element present at the top of the activity screen. It is a salient feature of an android application that has a consistent presence over all its activities. It provides a visual structure to the app and contains some of the frequently used elements for the users. Android ActionBar was launched by Google in 2013 with the r
3 min read
Difference Between AppBar, ActionBar, and Toolbar in Android
AppBar AppBar is a design element in an application's activity that has a significant role. Its appearance gives a unique identity to the application. Moreover, it displays the title of the current activity that facilitates users to know their location in the application. To give a consistent look to an application, developers use AppBar. Prior to
4 min read
How to Add Switch in Android ActionBar?
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 inacti
3 min read
How to Set Gradient and Image Backgrounds for ActionBar in Android?
UI plays quite significantly to keep the user engaged within the application. The very basic starts with developing a theme for an application. Themes may apply to all the UI elements within the application, but, the first thing that the user may notice is the Action Bar. Action Bar has a theme by default. We can only change its colors from availab
3 min read
How to Change ActionBar Title Programmatically in Android?
Whenever we develop an Android application and run it, we often observe that the application comes with an ActionBar with the name of the application in it. This happens by default unless explicitly changed. This text is called the title in the application. One can change the title of the application by making changes to the app_name string present
3 min read
How to Use Material Contextual ActionBar Library in Android App?
Let us first understand the two types of app bars in an android app: The Regular AppBarThe Contextual AppBar The Regular AppBar is just a normalized app bar that appears on the top of a page and can be well customized according to the user's requirements. It can be used to display page topics/company names/etc., clickable icons, navigation to other
7 min read
How to Get ActionBar Height in Pixels in Android?
ActionBar is a UI element that is generally empty but can consist menu and runs on top of the activity. The significance of ActionBar is that it displays the application name and can provide a menu to navigate to the user. The rest of the activity which is programmable is completely separate from the ActionBar. Hence, it is important to know the Ac
2 min read
Create Options Menu in ActionBar in Android using Jetpack Compose
In Android, ac ActionBar or a TopBar is a UI element that is present at the top of the activity screen. An ActionBar by default displays the activity name inside it. However, we can add other elements like the back button, images, options menu, etc inside an ActionBar. So in this article, we will show you how you could Create Options Menu in Action
3 min read
How to Use Fast Android Networking Library in Android with Example?
In Android, we know multiple networking libraries like Retrofit, Volley. We use these libraries specifically for making networking requests like performing actions on API. But Besides that, there is another library called Fast Networking Library which has a few advantages over other libraries. In this tutorial, we will be specifically focusing on l
4 min read
Android Jetpack - WorkManager with Example
WorkManager is an Android Jetpack library that provides a flexible and efficient way to schedule and manage background tasks in your app. It is a powerful and recommended tool for managing background processing in Android applications. With WorkManager, you can schedule asynchronous, deferred, and periodic tasks that need to run even when the app i
5 min read
Android BottomSheet Example in Kotlin
The Bottom Sheet is seen in many of the applications such as Google Drive, Google Maps and most of the applications used the Bottom Sheet to display the data inside the application. In this article, we will take a look at implementing a Bottom Sheet in the Android app using Kotlin in Android Studio. What is Bottom Sheet? Bottom Sheet is a component
5 min read
Spinner in Android with Example
Android Spinner is a view similar to the dropdown list which is used to select one option from the list of options. It provides an easy way to select one item from the list of items and it shows a dropdown list of all values when we click on it. The default value of the android spinner will be the currently selected value and by using Adapter we ca
4 min read
ImageView in Android with Example
ImageView class is used to display any kind of image resource in the android application either it can be android.graphics.Bitmap or android.graphics.drawable.Drawable (it is a general abstraction for anything that can be drawn in Android). ImageView class or android.widget.ImageView inherits the android.view.View class which is the subclass of Kot
4 min read
PhotoView in Android with Example
In this article, PhotoView is added to android. PhotoView aims to help produce an easily usable implementation of a zooming Android ImageView using multi-touch and double-tap. Besides that, it has many more features like it notifying the application when the user taps on the photo or when the displayed matrix gets changed. It provides smooth scroll
2 min read
NestedScrollView in Android with Example
NestedScrollView is just like ScrollView, but it supports acting as both a nested scrolling parent and child on both new and old versions of Android. It is enabled by default. NestedScrollView is used when there is a need for a scrolling view inside another scrolling view. You have seen this in many apps for example when we open a pdf file and when
5 min read
Bundle in Android with Example
It is known that Intents are used in Android to pass to the data from one activity to another. But there is one another way, that can be used to pass the data from one activity to another in a better way and less code space ie by using Bundles in Android. Android Bundles are generally used for passing data from one activity to another. Basically he
6 min read
Activity State Changes In Android with Example
Prerequisites: Activity lifecycle in android As it is known that every Android app has at least one activity associated with it. When the application begins to execute and runs, there are various state changes that activity goes through. Different events some user-triggered and some system triggered can cause an activity to do the transition from o
6 min read
Floating Action Button (FAB) in Android with Example
The floating action button is a bit different button from the ordinary buttons. Floating action buttons are implemented in the app's UI for primary actions (promoted actions) for the users and the actions under the floating action button are prioritized by the developer. For example the actions like adding an item to the existing list. So in this a
8 min read
Theming Floating Action Buttons in Android with Example
Prerequisite: Floating Action Button (FAB) in Android with ExampleExtended Floating Action Button in Android with Example Android application developers want to seek the attention of the users by customizing and theming the android application widgets and keep more traffic of customers only by the design of the application. In this article, it has
12 min read
ArrayAdapter in Android with Example
The Adapter acts as a bridge between the UI Component and the Data Source. It converts data from the data sources into view items that can be displayed into the UI Component. Data Source can be Arrays, HashMap, Database, etc. and UI Components can be ListView, GridView, Spinner, etc. ArrayAdapter is the most commonly used adapter in android. When y
3 min read
SlidingDrawer in Android with Example
SlidingDrawer is a common requirement in android mobiles to view the content whenever needed by sliding horizontally as well as vertically. In this article, let us check out Sliding Drawer which is used to hide the content out from the screen and allows the user to drag a handle to bring the content on the screen whenever needed in a very user-frie
9 min read
MVC (Model View Controller) Architecture Pattern in Android with Example
Developing an android application by applying a software architecture pattern is always preferred by the developers. An architecture pattern gives modularity to the project files and assures that all the codes get covered in Unit testing. It makes the task easy for developers to maintain the software and to expand the features of the application in
8 min read
ViewStub in Android with Example
In Android, ViewStub is a zero-sized invisible View and very flexible in that we can lazily inflate layout resources at runtime. It is a dumb and lightweight view and it has zero dimension. Depending upon the requirement, whenever in need we can inflate at runtime. This is a classic example to handle when there are complicated views to be handled.
6 min read
MVP (Model View Presenter) Architecture Pattern in Android with Example
In the initial stages of Android development, learners do write codes in such a manner that eventually creates a MainActivity class which contains all the implementation logic(real-world business logic) of the application. This approach of app development leads to Android activity gets closely coupled to both UI and the application data processing
12 min read
Include and Merge Tags in Android with Example
Android apps are growing and one important aspect of it is reusability. Sometimes, the complexity of app design will be more and during that time, Android providing very efficient reusable features by means of the <include/> and <merge/> tags. Under <merge/> tags, we can specify a part of the layout that has to come in the main la
4 min read
Theming of Material Design EditText in Android with Example
Prerequisite: Material Design EditText in Android with Examples In the previous article Material Design EditText in Android with Examples Material design Text Fields offers more customization and makes the user experience better than the normal text fields. For example, Icon to clear the entire EditText field, helper text, etc. In this article, it'
4 min read
Theming Material Design Snackbars in Android with Example
In the previous article, it's been discussed Snackbar Material Design Components in Android. In this article, it's been discussed how we can theme material design Snackbar and increase the User Experience. Theming Example 1:This method is done using the styles.xml file. Where we need to override the default style of the Snackbar.Have a look at the
5 min read
RecyclerView using GridLayoutManager in Android With Example
RecyclerView is the improvised version of a ListView in Android. It was first introduced in Marshmallow. Recycler view in Android is the class that extends ViewGroup and implements Scrolling Interface. It can be used either in the form of ListView or in the form of Grid View. How to use RecyclerView as GridView? While implementing Recycler view in
6 min read