Android Custom Action Bar Example Tutorial

Filed Under: Android

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="http://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.

Reference: Android Doc

Comments

  1. Amit says:

    use getActionBar() instead of getSupportActionBar()

    1. Anupam says:

      supportActionBar provides backward compatibility. It is recommended!

  2. Jorge J says:

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

  3. Mithun says:

    this code is not supporting for android API below 21

    1. MyName says:

      I should have read this one before.
      Shame he didn’t mention it. would saved me time

      1. Pankaj says:

        Are you seriously coding on below API 21 level? It’s not even supported by Google anymore and it’s more than 3 years old.

  4. Aayushman says:

    Can we inflate menu in this

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages