Tutorial

Android Custom Action Bar Example Tutorial

Published on August 3, 2022
Default avatar

By Anupam Chugh

Android Custom Action Bar Example Tutorial

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.

In this tutorial we will create an app that consists of Android Custom Action Bar with a custom layout. We assume that you have a basic understanding of the ActionBar component discussed in this tutorial.

Android Custom Action Bar

To customise an ActionBar first we need to configure the Theme in the res/values/styles.xml and set the theme for the respective activity class in the AndroidManifest.xml. Following is the xml layout for that: styles.xml

<resources>
    
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>

    <style name="CustomTheme" parent="Theme.AppCompat.Light">

        <item name="contentInsetStart">0dp</item>
        <item name="contentInsetEnd">0dp</item>
    </style>

</resources>

From the above snippet if we use AppTheme style for our activity, it will throw a null pointer exception as it explicitly specifies the NoActionBar theme. Hence we’ll use the CustomTheme style in this project. The contentInsetStart and contentInsetEnd are the padding values. Note that we will be using AppCompatActivity since it provides maximum compatibility with pre-3.0 Android versions.

Custom Action Bar Layout

Following is the view layout that will be set to the ActionBar from our MainActivity. custom_action_bar_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    >

    <TableRow>

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/back"
            android:layout_gravity="center_vertical"
            android:background="@android:color/transparent"
            android:id="@+id/action_bar_back"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:gravity="center_horizontal"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textStyle="bold"
            android:padding="10dp"
            android:layout_alignParentTop="true"
            android:layout_weight="1"
            />

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/forward"
            android:id="@+id/action_bar_forward"
            android:layout_gravity="center_vertical"
            android:background="@android:color/transparent"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true" />


    </TableRow>

</TableLayout>

The view layout consists of two ImageButtons that represent forward and back image buttons and a TextView in the center.

Android Custom Action Bar Project Structure

android custom action bar project

Android Custom Action Bar Code

The activity_main.xml is an empty RelativeLayout since our emphasis here is on the ActionBar. The MainActivity.java is given below.

package com.journaldev.customactionbar;

import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_action_bar_layout);
        View view =getSupportActionBar().getCustomView();

        ImageButton imageButton= (ImageButton)view.findViewById(R.id.action_bar_back);

        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        ImageButton imageButton2= (ImageButton)view.findViewById(R.id.action_bar_forward);

        imageButton2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"Forward Button is clicked",Toast.LENGTH_LONG).show();
            }
        });
    }


}

In the above code we’re using support libraries. Hence we’ve used getSupportActionBar() instead of getActionBar(). To add a custom layout to the ActionBar we’ve called the following two methods on the getSupportActionBar() :

  • getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
  • getSupportActionBar().setDisplayShowCustomEnabled(true);

setCustomView() is invoked to inflate the ActionBar with a customView as shown above. To set the onClickListeners for the ActionBar buttons we need to get the CustomView first using getCustomView(). In this tutorial we’ve programmed the back button to close the activity using finish(); and the forward button to display a Toast. Note : Add the following line in the AndroidManifest.xml inside the application tag.

android:theme="@style/CustomTheme"

Here is our android application with custom theme and layout. android custom actionbar example Note: There is a fixed margin on either sides that can’t be modified. For that we’ll need to replace the ActionBar with a ToolBar. We’ll discuss on that in a later tutorial. This brings an end to android custom action bar tutorial. You can download the final Android CustomActionBar Project from the below link.

Download Android Custom Action Bar Project

Reference: Android Doc

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

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
June 28, 2018

use getActionBar() instead of getSupportActionBar()

- Amit

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 18, 2018

    getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM); throws NullPointerException

    - Jorge J

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      June 29, 2017

      this code is not supporting for android API below 21

      - Mithun

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        April 17, 2017

        Can we inflate menu in this

        - Aayushman

          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!

          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
          DigitalOcean Cloud Control Panel