Android action bar was introduced to maintain a consistent navigation across the application. It has the powerful capabilities like adapting to screen configurations (landscape & portrait), prioritizing important actions, adding widgets to action bar (search, sharing etc.), providing navigation between screens (drop-down & tabbed navigation) and much more.

In this tutorial we are going to cover most of the action bar functionality. Some of the topics left for upcoming tutorials as they are pretty much lengthy.

android action bar tutorial

Overview of Action Bar

Action bar mainly contains four functional areas. They are app icon, view control, action buttons and action overflow.
App Icon – App branding logo or icon will be displayed here.
View Control – A dedicated space to display app 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.

Check out the following diagram for complete overview about action bar.

android action bar overview

Android version support below 3.0

Action bar is introduced in android 3.0 (API level 11), but if you want your app to support action bar in older versions too, then use Support Library to make it compatible with older versions (Android 2.1 and above)

Starting new Project

1. Create a new project in Eclipse from File ⇒ New ⇒ Android Application Project. While creating the project select Minimum SDK version to API 11 and select a theme with action bar. (I left my main activity name as MainActivity.java)

android-action-bar-creating-project

2. Android.com provides some useful icons for action bar. Download the Action Bar Icon Set and select the required icons and add them to the project. Copy each icon with all resolutions (xxhdpi, xhdpi, hdpi, mdpi) into respected folders in Eclipse project under res ⇒ drawable- folders.

Adding Action Bar Icons

Once you are done copying required icons, we will start adding the action items first. The action bar uses the same older menu method to show action items.

3. Create a new xml file under res ⇒ menu named activity_main_actions.xml and add the following code. Here each <item> indicates each action item.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- Search / will display always -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          android:showAsAction="ifRoom"/>
    
    <!-- Location Found -->
    <item android:id="@+id/action_location_found"
          android:icon="@drawable/ic_action_location_found"
          android:title="@string/action_location_found"
          android:showAsAction="ifRoom" />
    
    <!-- Refresh -->
    <item android:id="@+id/action_refresh"
          android:icon="@drawable/ic_action_refresh"
          android:title="@string/action_refresh" 
          android:showAsAction="ifRoom" />
    
    <!-- Help -->
    <item android:id="@+id/action_help"
          android:icon="@drawable/ic_action_help"
          android:title="@string/action_help" 
          android:showAsAction="never"/>
    
    <!-- Check updates -->
    <item android:id="@+id/action_check_updates"
          android:icon="@drawable/ic_action_refresh"
          android:title="@string/action_check_updates"
          android:showAsAction="never" />
</menu>

Here the important xml attributes should be known are

android:icon – Defines the icon of the action item.
android:title – Title for the icon.
android:showAsAction – Defines the visibility of the action item. It accepts following values.

ifRoom Displays the icon if there is space available on the screen
never Never places this icon on the action bar
always Forces to display the icon always irrespective of space available. This way is not suggested.
withText Displays a text along with the icon. Normally the text value defined by android:title will be displayed
collapseActionView Defines the action layout associated with it. This action view defined using android:actionLayout or android:actionViewClass

4. Now open your main activity class and do the following in onCreateOptionsMenu() method.

public class MainActivity extends Activity{

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main_actions, menu);

		return super.onCreateOptionsMenu(menu);
	}
}

Now if you run the project, you can see the action bar with action icons. You can also notice that an overflow icon shown which opens the unimportant action items as a drop down menu.

android action bar action icons

Handling Action Bar Icon Click Events

Until now we displayed action bar action items, but we haven’t enabled the interaction with action items. Let’s add click event listener to action items now.

5. Open your main activity and override onOptionsItemSelected() method. This method accepts menu item as a parameter. Selected action item can be identified by using it’s id. Normally a switch case statement is suggested for this purpose. You can perform appropriate action in the matched case block.

public class MainActivity extends Activity{
...
...

	/**
	 * On selecting action bar icons
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Take appropriate action for each action item click
		switch (item.getItemId()) {
		case R.id.action_search:
			// search action
			return true;
		case R.id.action_location_found:
			// location found
			LocationFound();
			return true;
		case R.id.action_refresh:
			// refresh
			return true;
		case R.id.action_help:
			// help action
			return true;
		case R.id.action_check_updates:
			// check for updates action
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Launching new activity
	 * */
	private void LocationFound() {
		Intent i = new Intent(MainActivity.this, LocationFound.class);
		startActivity(i);
	}
}

Enabling Up / Back Navigation

Action bar also provides the feasibility of back navigation when the app involves hierarchical relationship between screens. Please note that this behavior is not the same as android system back button. A small back arrow icon will be displayed before action bar icon when up navigation is enabled. Follow these steps to enable up navigation.

Enabling up navigation involves two steps.
> Defining the parent activity in the AndroidManifest.xml file
> Enabling the up navigation in the activity class.

To test this scenario I have created another activity and enabled the up navigation in that activity. If you observe the above section, I have launched LocationFound activity in the menu selection block. So let’s create required files for that activity.

7. Create the layout file for this activity named activity_location_found.xml under res ⇒ layout folder.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" 
    android:padding="10dp">
    
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Location is found. Drop a Message here"/>    

</LinearLayout>

8. Create a new class under you main package named LocationFound.java and paste the following code.

Action bar Up navigation can be enabled by calling setDisplayHomeAsUpEnabled(true) method on to action bar. By calling this function a back arrow will be displayed on the action bar.

package info.androidhive.actionbar;

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;

public class LocationFound  extends Activity {

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

		// get action bar	
		ActionBar actionBar = getActionBar();

		// Enabling Up / Back navigation
		actionBar.setDisplayHomeAsUpEnabled(true);
	}
}

9. Also we need to add the new activity in AndroidManifest.xml file. Here we have to mention the parent activity to which the up navigation is pointing to by using android:parentActivityName property.

<!-- Location found activity -->
        <activity
            android:name="info.androidhive.actionbar.LocationFound"
            android:label="@string/activity_new_message"
            android:parentActivityName="info.androidhive.actionbar.MainActivity" >
        </activity>

Run the project and check it once.

android action bar up back navigation

Hiding / Showing the Action Bar in Particular Activity

In some cases you might wanted to hide the action bar in particular activity. You can hide and show the action bar by calling hide() and show() methods.

ActionBar actionBar = getActionBar();
// hide the action bar
actionBar.hide();

// show the action bar
actionBar.show();

Changing the Action Bar Icon

Action bar by default displays the application icon which was set using android:icon in the AndroidManifest.xml file. So if you want to change the action bar icon, you can do it by calling setIcon(drawable) on to action bar.

ActionBar actionBar = getActionBar();

// set the icon
actionBar.setIcon(R.drawable.ico_actionbar);
android action bar changing the icon

Enabling Split Action Bars

Split action bar provides a separate bar at the bottom of the screen. This option will be useful when you want to display the action items at the bottom of the screen by leaving some space on the title bar.

To enable split action bar add uiOptions=”splitActionBarWhenNarrow” to all the <activity> tags or to the <application> tag directly in AndroidManifest.xml file. Also we need to add <meta-data> with the value android.support.UI_OPTIONS to support older version below API level 14.

        <!-- Location found activity -->
        <activity
            android:name="info.androidhive.actionbar.LocationFound"
            android:label="@string/activity_location_found"
            android:parentActivityName="info.androidhive.actionbar.MainActivity" >
            <!-- To support below API Level 14 -->
            <meta-data android:name="android.support.UI_OPTIONS"
                   android:value="splitActionBarWhenNarrow" />
        </activity>
android enabling split action bar

Once again run the project and check whether you are getting split action bar or not.

Adding Search Widget to action bar

Another most useful feature of action bar is adding widgets to it. For example like adding search widget to action bar. Search widget will be useful when user wants to search for something in the app or across android OS.

Adding search widget involves these steps.

> Adding the Search Widget to action bar action item
> Defining the searchable configuration in the xml
> Creating the activity to handle search query and display the results
> Defining the default searchable activity and SEARCH intent filter in AndroidManifest.xml file

10. So first we add the search widget to action bar. Open your activity_main_actions.xml which is located under menu folder and add search widget to search action item as below. android:actionViewClass=”android.widget.SearchView

    <!-- Search Widget -->
    <item android:id="@+id/action_search"
          android:icon="@drawable/ic_action_search"
          android:title="@string/action_search"
          android:showAsAction="always"
          android:actionViewClass="android.widget.SearchView"/>

11. Create a searchable configuration file under res ⇒ xml folder named searchable.xml (If you don’t see xml folder under res, create a new folder with the name xml). See list of Searchable Configuration options.

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
    android:hint="@string/search_hint"
    android:label="@string/app_name" />
It is suggested that always assign the values of android:hint and android:label from strings.xml file only instead of writing the values directly.

Now open the main activity and modify the code in the onCreateOptionsMenu() method.

@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.activity_main_actions, menu);

		// Associate searchable configuration with the SearchView
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
				.getActionView();
		searchView.setSearchableInfo(searchManager
				.getSearchableInfo(getComponentName()));

		return super.onCreateOptionsMenu(menu);
	}

12. We need another activity to handle search query and results. Create a new class named SearchResultsActivity.java and paste following code. Also create layout file too named activity_search_results.xml.

Here I just passed the search query to another activity. You have to take appropriate action to display the search results using the query either from SQLite database or making a request to server and getting the results or some other way.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/txtQuery"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    

</RelativeLayout>
package info.androidhive.actionbar;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class SearchResultsActivity extends Activity {

	private TextView txtQuery;

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

		// get the action bar
		ActionBar actionBar = getActionBar();

		// Enabling Back navigation on Action Bar icon
		actionBar.setDisplayHomeAsUpEnabled(true);

		txtQuery = (TextView) findViewById(R.id.txtQuery);

		handleIntent(getIntent());
	}

	@Override
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		handleIntent(intent);
	}

	/**
	 * Handling intent data
	 */
	private void handleIntent(Intent intent) {
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);

			/**
			 * Use this query to display search results like 
			 * 1. Getting the data from SQLite and showing in listview 
			 * 2. Making webrequest and displaying the data 
			 * For now we just display the query only
			 */
			txtQuery.setText("Search Query: " + query);

		}

	}
}

13. Finally in the AndroidManifest.xml file define the searchable configuration, default searchable activity and the activity performing the search.

android.app.default_searchable – Defines the default searchable activity handle search. You can add this block anywhere in the manifest file either inside <application> tag or <activity> tag.
android.app.searchable – Defines the searchable configuration which was written in searchable.xml file
android.intent.action.SEARCH – Should be defined as a intent filter for the activity which receives the search query.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="info.androidhive.actionbar"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="11"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="info.androidhive.actionbar.MainActivity"
            android:label="@string/app_name">
            <meta-data
                android:name="android.app.default_searchable"
                android:value=".SearchResultsActivity" />

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <!-- Search results activity -->
        <activity android:name=".SearchResultsActivity"
            android:parentActivityName="info.androidhive.actionbar.MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.SEARCH" />
            </intent-filter>

            <meta-data
                android:name="android.app.searchable"
                android:resource="@xml/searchable" />
        </activity>

        <!-- Location found activity -->
        <activity
            android:name="info.androidhive.actionbar.LocationFound"
            android:label="@string/activity_location_found"
            android:parentActivityName="info.androidhive.actionbar.MainActivity" >
        </activity>
    </application>

</manifest>
android action bar adding search widget

Action bar provides two kinds of navigational options to switch between views. One is Tabbed navigation and other is Spinner Drop down navigation.

Adding Spinner Drop-down Navigation

Action bar has the inbuilt capability of adding spinner drop down to switch b/w views. This navigation is suggested when your app view switching is not much frequent.

The spinner I am adding here is using a custom list adapter where the list item will have a icon and text like Google Maps App. I gathered all the required icons for the list and placed them under drawable folders with different resolutions.

14. Create a new package named info.androidhive.actionbar.model to store the model classes. For spinner list item create a model named SpinnerNavItem.java under this package. This model class contains two elements, title and image for the list item.

package info.androidhive.actionbar.model;

public class SpinnerNavItem {

	private String title;
	private int icon;
	
	public SpinnerNavItem(String title, int icon){
		this.title = title;
		this.icon = icon;
	}
	
	public String getTitle(){
		return this.title;		
	}
	
	public int getIcon(){
		return this.icon;
	}
}

15. Each list item needs a layout file which contains a image and text. Create a xml layout file under res ⇒ layout folder named list_item_title_navigation.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="fill_parent"
    android:padding="5dp" >
    
    <ImageView android:id="@+id/imgIcon"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/ic_launcher"
        android:layout_marginRight="5dp"
        />
    
    <TextView android:id="@+id/txtTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/imgIcon"/>

</RelativeLayout>

16. Now we need another package to keep our adapter classes. Create a new package with the name info.androidhive.info.actionbar.adapter. The adapter class for spinner list I am creating is TitleNavigationAdapter.java

package info.androidhive.info.actionbar.adapter;

import info.androidhive.actionbar.R;
import info.androidhive.actionbar.model.SpinnerNavItem;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class TitleNavigationAdapter extends BaseAdapter {

	private ImageView imgIcon;
	private TextView txtTitle;
	private ArrayList<SpinnerNavItem> spinnerNavItem;
	private Context context;

	public TitleNavigationAdapter(Context context,
			ArrayList<SpinnerNavItem> spinnerNavItem) {
		this.spinnerNavItem = spinnerNavItem;
		this.context = context;
	}

	@Override
	public int getCount() {
		return spinnerNavItem.size();
	}

	@Override
	public Object getItem(int index) {
		return spinnerNavItem.get(index);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) { 
        if (convertView == null) {
        	LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.list_item_title_navigation, null);
        }
        
        imgIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
        txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
        
        imgIcon.setImageResource(spinnerNavItem.get(position).getIcon());
        imgIcon.setVisibility(View.GONE);
        txtTitle.setText(spinnerNavItem.get(position).getTitle());
        return convertView;
	}
	

	@Override
	public View getDropDownView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
        	LayoutInflater mInflater = (LayoutInflater)
                    context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.list_item_title_navigation, null);
        }
        
        imgIcon = (ImageView) convertView.findViewById(R.id.imgIcon);
        txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
        
        imgIcon.setImageResource(spinnerNavItem.get(position).getIcon());        
        txtTitle.setText(spinnerNavItem.get(position).getTitle());
        return convertView;
	}

}

17. Now open the main activity and implement the class from ActionBar.OnNavigationListener to handle the spinner select listener.

public class MainActivity extends Activity implements ActionBar.OnNavigationListener{

18. Adding spinner drop down to action bar involves few steps.

> First hide the action bar title using setDisplayShowTitleEnabled(false)
> Second enable the action bar spinner navigation mode using
setNavigationMode(ActionBar.NAVIGATION_MODE_LIST)
> Then create a adapter and assign it to action bar using setListNavigationCallbacks()

Following is the complete code to enable to action bar spinner navigation

package info.androidhive.actionbar;

import info.androidhive.actionbar.model.SpinnerNavItem;
import info.androidhive.info.actionbar.adapter.TitleNavigationAdapter;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;

public class MainActivity extends Activity implements ActionBar.OnNavigationListener{

	// action bar
	private ActionBar actionBar;

	// Title navigation Spinner data
	private ArrayList<SpinnerNavItem> navSpinner;
	
	// Navigation adapter
	private TitleNavigationAdapter adapter;

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

		actionBar = getActionBar();
		
		// Hide the action bar title
		actionBar.setDisplayShowTitleEnabled(false);

		// Enabling Spinner dropdown navigation
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
		
		// Spinner title navigation data
		navSpinner = new ArrayList<SpinnerNavItem>();
		navSpinner.add(new SpinnerNavItem("Local", R.drawable.ic_location));
		navSpinner.add(new SpinnerNavItem("My Places", R.drawable.ic_my_places));
		navSpinner.add(new SpinnerNavItem("Checkins", R.drawable.ic_checkin));
		navSpinner.add(new SpinnerNavItem("Latitude", R.drawable.ic_latitude));		
		
		// title drop down adapter
		adapter = new TitleNavigationAdapter(getApplicationContext(), navSpinner);

		// assigning the spinner navigation		
		actionBar.setListNavigationCallbacks(adapter, this);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	....
	}

	/**
	 * On selecting action bar icons
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	...
	}

	/**
	 * Actionbar navigation item select listener
	 * */
	@Override
	public boolean onNavigationItemSelected(int itemPosition, long itemId) {
	// Action to be taken after selecting a spinner item
		return false;
	}
}
android action bar adding spinner drop down

Adding Tab Navigation

Another navigation action bar provides is tabbed navigation. This way is suggested when the navigation is too frequent between views. I already explained tab navigation in my previous article Android Tab Layout with Swipeable Views in a detailed manner. Follow the tutorial to enable the tabbed navigation with swipe gestures.

android action bar adding tab navigation

Adding Custom Views – Refresh and Loading

Action bar also provides an option to add a custom view apart from widgets. You can see lot of apps uses refresh icon and progress loader views while making a HTTP requests to sync the data. That can be done in a easy way.

19. First we will create a custom view which we want to show in the action bar. We will create a simple layout with progress bar. Create a new xml layout file under res ⇒ layout folder named action_progressbar.xml

<?xml version="1.0" encoding="utf-8"?>
<ProgressBar xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
     android:layout_height="wrap_content">
        
</ProgressBar>

20. As you can see we have kept a refresh action item in our action bar. Open your main activity class and do the following changes.

What we are doing here is, when user selects the refresh action item we need to get the data from server using Async task. Before sending a request, using onPreExecute() method we set a custom layout in refresh action item. In doInBackground() method we send the request to server and once we go the result from server, in onPostExecute() method we remove the custom progress layout.

package info.androidhive.actionbar;

import info.androidhive.actionbar.model.SpinnerNavItem;
import info.androidhive.info.actionbar.adapter.TitleNavigationAdapter;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;

public class MainActivity extends Activity implements
		ActionBar.OnNavigationListener {

	// action bar
	private ActionBar actionBar;

	// Refresh menu item
	private MenuItem refreshMenuItem;

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

		actionBar = getActionBar();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	....
	}

	/**
	 * On selecting action bar icons
	 * */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Take appropriate action for each action item click
		switch (item.getItemId()) {
		...
		case R.id.action_refresh:
			// refresh
			refreshMenuItem = item;
			// load the data from server
			new SyncData().execute();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	/**
	 * Async task to load the data from server
	 * **/
	private class SyncData extends AsyncTask<String, Void, String> {
		@Override
		protected void onPreExecute() {
			// set the progress bar view
			refreshMenuItem.setActionView(R.layout.action_progressbar);

			refreshMenuItem.expandActionView();
		}

		@Override
		protected String doInBackground(String... params) {
			// not making real request in this demo
			// for now we use a timer to wait for sometime
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String result) {
			refreshMenuItem.collapseActionView();
			// remove the progress bar view
			refreshMenuItem.setActionView(null);
		}
	};

}

Run the project and test the progress loader once. If you can’t see the refresh icon, rotate the emulator into landscape mode. (Use Ctrl + F11 to rotate the emulator)

android action bar adding custom view refresh progress bar

There is a lot more customization can be done to action bar. I’ll cover those topics in my upcoming tutorials.

Ravi is hardcore Android programmer and Android programming has been his passion since he compiled his first hello-world program. Solving real problems of Android developers through tutorials has always been interesting part for him.
  • Arash

    It was great ! nice job

  • Ramiz Mohamed

    Well done Ravi, brilliant as always.

  • Vijith

    Great!

  • The limitation of the using SearchView is that we can only search a single table in the Android app. It does not work if we have multiple tables in the database. If you cant understand please see my question on the StackOverflow.com

    http://stackoverflow.com/questions/19679569/search-suggestions-from-different-tables-in-different-activities

  • Selva

    Nice article

  • Mahmudul

    That is really a nice tutorial ever in Action Bar.

  • tom

    It was great !
    but, how to add Action to be taken after selecting a spinner item?

    • You have to write click listener in spinner adapter class.

  • Anas

    Thank’s a lot that’s very helpful

  • max

    Thanks a lot !
    But I realize when I test search function. When I got my Search Result then I have to click 2 times to button BACK (device or Back Navigation on Action Bar) to back MainActivity.

  • Gaurav Mahajan

    nice tutorial! thanks

  • Madan

    This tutorial is nice could please clarify the below doubts
    how to continue further Search on search activity, how to close the searchview after search, and also how to open searchview with some text (probably with the last search string).

    • You can use sqlite and display the results which matches the search query or you can make a server request and display the results. This depends more on you app requirement.

  • droidgeek

    done a superb job.

  • Mohammad

    excellent job…thanks!!

  • Ravi

    Can you provide tutorial to to implement action bar in android 2.1 and 2.3 as this works only with higher version (versions with API level 11 or higher). I need Tutorial for version with API level 7 and higher.

  • jaaps

    great work… thanks!

  • Candroid

    Thanks! This is very useful

  • Muhammad Lazarwardi Jamaludin

    Excellent tutorial!!! But i wonder how to connect sqlite and get data from query. Can you show me how to do it?

  • Miguel

    I tried to add the support library so I can support gingerbread, but still there is an error on getActionBar, telling me to suppress the link or use TargetApi, when I choose the TargetApi, when I click the search button, the ActionBar turns white (originally black). Why is this?

    • thinknirmal

      When using the support library it should be:
      getSupportActionBar()

  • Aiman Baharum

    Hey first of all thanks for making this tutorial. I was wondering how do I make a Refresh button “alive”? I mean what kind of request does the Refresh action should have in order to make it runnable in the background and refresh the activity?

    thanks

  • Manoj

    Hi,

    Can anyone look into this.
    http://stackoverflow.com/questions/18079304/remove-actionbar-tabs-padding-in-android

    I am facing problem of spacing on left-right on tab-bar when I have two tabs.

  • Matthias Klan

    wow thank you so much! Great tutorial

  • hattori hanzo

    thank you guy, you helped me a lot

  • Akshata

    Hi. great tutorials. I Have a question for u, Can i link an action-bar tab to activity instead of fragment? i hope the question makes sense to you.

  • Steve

    I could not get the splitActionBarWhenNarrow to work. I did some searching and found that if I added android:uiOptions=”splitActionBarWhenNarrow” to the activity rather than android:value=”splitActionBarWhenNarrow” as metadata it worked great. Not sure if this is a typo in your example or if I did something wrong.

  • Nageshwarrao

    First thanks for making this example,It is with the Actionbar the How can we provide same search functionality to the Edit Text

  • Munaf

    Excellent …. it works fine for android 11, am trying to add spinner for android 2.x could you please modify your code so that it works for 2.x ……………………………..

  • Mathieu

    Thanks again for your great help!

  • sarina

    how to implement action bar for android 2.3.6 version

  • Guest

    It’s very good , But I can’t download source Code. Can you share it again , Thanks

  • Guest

    I can’t download source code , can you help ? Thanks

  • Sohail Zahid

    Aweeesome Dude God bless you everyday……..

  • Khalid Rajai Kadamani

    I am finding it so hard!!! a lot of codes and I can’t focus
    how I can simplify this example more ??

  • lakhwinder singh

    Thanks ravi you are really doing the good job..

  • Hi I followed your tutorial and created one action bar, but i am unable to add the actions to them, really not sure why, if you can help, we can discuss on the same, please reply or drop me an email to infonetzatinfonetzonlinedotcom, thanks million in advance.

  • Steve A

    Excellent resource, thank you!

  • Mohan Mugi

    Its really useful and too good tutorial

  • Mohan Mugi

    Thanks a lot

  • Mitesh Shah

    How can i align the text of action bar to center??

    • wenbin liu

      You may getActionBar().setCustomView(R.layout.YOUR_LAYOUT);
      and in your layout file, centering your text

      • Guest

        Thats fine..!! 🙂 but problem comes for Back Navigation…:(

      • Mitesh Shah

        Thats Fine….!!!! 🙂 But problem comes for Back Navigation..???? 🙁

  • Priyank

    awesome tutorial

  • melandrageem

    my overflow doesnt show… i dont know why cause i follow your instruction except for the minimum API… i’m using API 8 and i’ve done the support library…

    nice tutorial dude .. 😀 i enjoy learning with you

    • XYZ

      In the devices having hardware menu button, overflow icon will not be visible by default.You need to press the hardware menu button.

      Hope it helps 🙂

      • Ruitzei

        Wow thx, I almost drove crazy trying to guess why it wouldn’t show the overflow icons on devices with the hardware menu bottom!

  • Laven Pillay

    Hi, this is a very well done tutorial. Thank you so much for taking the time and effort to share this !

  • abida

    thank you so very much for this usefull tutorial

  • x

    How can i display the MAP here???

  • derdus

    God bless u very much, well done

  • Mostafa

    thnx very much

  • Qiang Fu

    really really awesome for beginner!

  • anniejuf

    it’s really help me in learning android programming. Thanks!

  • eslam

    how can i make easy share for text

  • subha s

    Possible to change the Navigation position. I mean now its showing in the top of the screen i need to add one image view in the top and below that i need navigation below another linear layout is this possible ??

  • Kumaro

    Best ActionBar Tutorial !!!!! THX a lot! 🙂

  • Rage

    How can i always display the bottom bar and not “splitActionBarWhenNarrow” ..

    Nice tutorials BTW.. good work (y)

  • manish

    i’m on starting of my app development…i can’t see overflow menu after running app in my mobile.. i tried everything but i couldn’t..pls help me…

  • dikshith

    i can.t see the overflow menu

  • Sukan M

    Thanks 🙂 I’m working on Action bar with Spinner..in the 18th step!..How can i get the selected items inside OnOptionsItemSelected ?

  • Pavan

    Hi sir.. Really great work. Thank you so much for your details.. I need one help from you. I want to build Quiz application which consists of 4 categories like “SPORTS”, “HISTORy” and each category should level1, level2,level3. User can select any levels in category. He as to share his score to facebook and RSS feed to get questions from websites. please help me develop this application. please help me pampapati.h@gmail.com

  • Pradip

    Nice turorial Thanks!!! In search widget i want to perform web request and display data on another activity. I am getting data from web service but when i redirect to another intent and pass data using intent.putExtra() i am getting null pointer exception..can you please tell me what wrong i am doing??? Some of the code snippet is as follows

    String query = intent.getStringExtra(SearchManager.QUERY);

    // This is to get json object from web service

    JSONObject jsnobject = com.snsd.util.UrlUtil.searchKshetraUrl(query);
    //Getting data from web service
    String kshetraId = jsnobject.getString(Constants.TAG_KSHETRA_ID);

    //This is to start new intent

    Intent newIntent = new Intent(SearchKshetraResult.this, KshetraDetails.class);

    // Closing all the Activities

    newIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    // Add new Flag to start new Activity

    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    intent.putExtra(Constants.TAG_KSHETRA_ID, txtQuery.getText().toString());

    startActivity(newIntent);

    Here im gettin “kshetraId” from web service and i am passing it to next activity but getting error on following line in next activity while retrieving it with

    String kshetraId = intent.getExtras().getString(Constants.TAG_KSHETRA_ID);

  • flyaway

    Something has been driving me nuts about the changes with ADT 14. It’s probably a simple fix that I am just overlooking, but here it is.

    ‘switch’ with ‘case’ no longer works, and you have to convert it to ‘if-else’. I can successfully update the code with no errors, but running it on the emulator, it crashes.

    Do you have any suggestions for translating ‘switch’ to ‘if-else’ besides using the Quick-Fix in Eclipse?

  • So beautiful

  • Vinay Maneti

    Hi, i have followed your tutorial and i added the spinner in the action bar but at present i want to move the action bar to right side . how to change the spinner position to right of the action bar..please can you suggest me the code….

  • Zeeshan rasool

    Great Work

  • Mta Umer

    Amazing grace. how sweet

  • Yonny

    Thanks, Bro. You helped a lot

  • hastha

    nice tutorial ,it’s very good..

  • Amit Singh

    Great explanation.

  • saman

    how change the action bar icons inside the tab activity

  • Ranjith Kumar

    pls tell me how to add support library? i know it but i want to conform what i know is right or not. Actually i want to implement action bar in my gingerbread version… pls help 🙂

    • Ranjith Kumar

      @disqus_WuSlDgk9sM:disqusi have tried that already but it is showing “unable to instantiate activity component info error and noSuchMethodFound error on gingerbread!@chris

      • ranjithstar256

        hi chris i have successfully implemented action bar in ginger bread version. Check this one! here you will get step by step procedures to implement action bar in ginger bread version click here
        follow all procedures correctly,you have to make some more changes also
        follow that. then it will work for sure. i have implemented it
        successfully. http://stackoverflow.com/q/23784067/2811343 <– check here

  • cello

    thx dude! great turtorial!

  • vijay

    Excellent tutorial, thanks for covering most of the action bar stuff.

  • krish

    thnks .its good and easy to learn

  • ranjithstar256

    Ravi Bro i have added support library to the application and its now working bro 🙂 here is the link for step by step procedure to implement this one. http://stackoverflow.com/q/23784067/2811343 🙂 i hope this may be useful for beginners bro 🙂 Thanks

  • Mario Cayer

    Here is my structure:

    MainActivity.java
    Activity01.java
    Activity02.java
    Activity03.java
    Help.java

    In my MainActivity.java
    I put 3 buttons that connect me to one activity .
    In each activity , I have an ActionBar with a back navigation to return to the previous activity.
    Each activity is declared in my Manifest with his android:parentActivityName .
    (In this case it is the MainActivity parent)

    I also have a Help.java activity. It is a simple explanatory program file and it can be called by the menu on each activity . The problem is that I can not give him one address parent activity
    (which is necessarily MainActivity ) because I can not define just a single parent file activity in the Manifest .

    For example, if I ‘m in Activity02 and I select Help from the menu ,, he returns to me MainActivity instead of Activity02 …

    Without having to create one help file for each activity , how can I just go back to the real parent activity that called activity Help ?

  • B.rohit Nare

    Can we implement the same action bar for Navigation drawer fragments in listview ?
    Or how to implement search component to fragments ?

  • oollff

    Amazing tutorial, had no problem implementing this with fragments (after reading the fragment page on android developers). Splendid work!!! (Just add “an” before vowel sounds and “a” for the rest, like “an icon” not “a icon).

  • Musashi Miyamoto

    Very nice. It’s all I need. Congrats

  • AFRODESCENDIENTE

    Ok i have my spiner but now how do i make it work?

  • Paul_Verest

    Thanks for sharing. This article needs a bit polishing, but content is good.

    It is strange but LocationFound Activity with its simple code and layout cause app to be stopped.

  • Lupita Llamas

    no sabes explicar, porfavor sigue una secuencia

  • hunterharada

    i have no dimen and something that should be inside that, anyone can help me?
    can i just sign a value like “30dp”?

  • Eugene

    Hi! How can i set search widget at the top of layout while my action bar is at bottom?

  • santosh singh

    I have added icons on tabs but not changing the color of icon when selecting . I want tabs like Facebook when i selected the the particular tab the icon color should changed

  • amay

    hello, anyone help me, how get item selected Spinner Drop-down Navigation Action Bar ? i use String selected = spinner.getSelectedItem().toString(); not appear right

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

    actionBar = getActionBar();

    // Hide the action bar title
    actionBar.setDisplayShowTitleEnabled(false);

    // Enabling Spinner dropdown navigation
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

    // Spinner title navigation data
    navSpinner = new ArrayList();
    navSpinner.add(new SpinnerNavItem(“Local”, R.drawable.ic_location));
    navSpinner.add(new SpinnerNavItem(“My Places”, R.drawable.ic_my_places));
    navSpinner.add(new SpinnerNavItem(“Checkins”, R.drawable.ic_checkin));
    navSpinner.add(new SpinnerNavItem(“Latitude”, R.drawable.ic_latitude));

    // title drop down adapter
    adapter = new TitleNavigationAdapter(getApplicationContext(), navSpinner);

    // assigning the spinner navigation
    actionBar.setListNavigationCallbacks(adapter, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    ….
    }

    /**
    * On selecting action bar icons
    * */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

    }

    /**
    * Actionbar navigation item select listener
    * */
    @Override
    public boolean onNavigationItemSelected(int itemPosition, long itemId) {
    // Action to be taken after selecting a spinner item
    return false;
    }

  • masoud

    excellent tutorial!!

  • Ramakrishna Dondapati

    Nice explanation! You could have mentions about UI (Action bar, Icon, text-field for ldpi/hdpi/xdpi/xhdpi and etc.) dimensions as well.

  • Garima

    how can we customize back navigation icon. suppose i want to change the color of this arrow buton, how can we do this?

  • dhnjy 18

    Hi, I am using support libraries for Action Bar on lower android versions, its doing well but while using splited action bar, android lower versions do not showing splited action bar and android heigher versions does. So where is the issue? How can I solve this?

    Hey I found this add following lines to your activity tag

    Its working now………

  • Jayesh Sanghani

    hi ravi bhai,

    i used code for search in action bar same as defined as this portal. But how to detect event when i close search widget.

  • asdec90

    awsome……….!!!!!!!!!!!!!!!!

  • Rock Tldr

    Could you please post a tutorial of action bar supporting old version of android? Cant use getActionBar() using the support v7 library

  • drucks87

    Hi, how i can use the method getsupportactionbar and at the same time PreferenceActivity?

    Thanks!

  • Jo

    Nice Article and thanks for sharing .Please let me know how can we remove the Header of the Spinner from appearing.

  • Shakeel

    You are doing great job man. Welldone . Ap k website bhot helpful ha.

  • Maulana Rocky

    Thanks for the tutorial, but i have a question.
    i want to change backgroud color action bar but i don’t, i have already use the resource in style and in oncreate i build the code //actionBar.setBackgroundDrawable(new ColorDrawable(Color.RED));
    but the result is same… action bar color is awlays black, please sir tell me….

    thank you

    • Maulana Rocky

      TQ sir, it’s done 🙂

    • Maimoona Khawaja

      how you resolved it?

  • Pasha Antya

    This is a very useful tutorial)
    Thank you)

  • rholand04

    how so very helpful for us.. thank u

  • Himanshu

    thanks bro nice tut i m looking forward for more 🙂

  • Akash KV

    Tnx

  • Download link not work for me, can anyone give me new link for downlaod source?

  • sharvan jain

    Thank you

  • sharvan jain

    Sir i have a doubt i.e. how to show the other icons with the text when any user clicks on the overflow icon?

  • Parth Nayak

    It’s great tutorial..but one question that this code is perfectly run on android emulator but in my android phone(4.2.2) overflow menu is not showing except that everything works perfect..So can you help me how to show that in my phone..

    • Pankaj Saxena

      same here

  • kszere

    What changes icon app in action bar to custom icon?

    • Alex Doyal

      The following two lines in your MainActivity’s onCreate:

      ActionBar actionBar = getActionBar();

      actionBar.setIcon(R.drawable.ico_actionbar);

      Where ico_actionbar is the id of the icon you added to your drawable folder.

  • dani

    hi
    thanks
    how want change the color and make a title for action bar ?

  • johnomanolo

    great tutorial! “There is a lot more customization can be done to action bar. I’ll cover those topics in my upcoming tutorials.” – did you make those? can’t seem to find them. I have some problems with home button and custom layout, would love to see you follow up on it.

  • Peddiraju Ginnedumu

    Is overflow icon added by us or automatically created??

    • Alex Doyal

      Automatically created.

  • Mahmoud Mrad

    that’s good but all actions are showing in overlfow icon,nothing is showing in the action bar..i mean the search icon doesn’t appear in the action bar,only “Search” word appear when pressin the overflow icon..i want the search to appear in the actionbar and users see the icon directly please help

    • Azmul Haq

      Make your search item always shown in menu.xml file..

  • Michael

    I’m a newbie, and this site has helped and still helping a lot! thanks guys

  • Shruti

    Nice Tutorial , it helped me very much, Thanx

  • No resource identifier found for “android:parentActivityName”.
    I am getting this error. Please help me out to solve this problem.

    Complete steps … Thanks

  • 정원혁

    What a wonderful tutorial! You saved my life!!!

  • Govindarajan D

    Thank you 🙂

  • Arvind

    Thanks Ravi, this is realy very helpful. nad i am waiting for new tutorials.

  • Chetan Deep

    Awesome solution…thanks man!..could not find the right sol anywhere else

  • Imran Muneer

    I have added code until step 9. But my activity locationfound is not starting and the class location found is not run. but when i click on location icon, app crashed. Can you tell me the problem? how i can check the activity created in main java class not executed?

    • Azmul Haq

      You need to check your logcat window..

  • kanika

    thank you for the tutorial. Can you help me? In my application, I have created a action bar & menu item is created with custom layout to show a count in textview along with a icon. Now I need to show & hide this icon based on the count. but I cannot figure out a way to do this. Any help is much appreciated.

    • Azmul Haq

      I think make visible and invisible your icon by comparing your count..

  • Aman

    i was added icons on actionbar but the icons was not displayed .what is the issue? how can i solve this

    • Aman

      and i have added code until step 11

  • Alam

    nice tutorial. i have question, how to drop down list of item from custom header instead of action bar.

  • Azmul Haq

    I am using action bar with view pager. view pager showing fragments and fragment has a floating button. I set view pager scrolling behaviour as you set in working with tabs tutorial. When fragment loads the floating button disappear below the screen and action bar overlaps the viewpager. Please give me the solution.. …

  • Homen

    Nice tutorial…

  • Jay

    Thanks Ravi….ur explanation and step to step demonstration
    is superb….after hours of search finally u resolved my problem….kudos….keep posting…ur awesome!!!

    • Hi Jay, be sure to follow the material design article.
      http://www.androidhive.info/2015/04/android-getting-started-with-material-design/

      • umme sulaith

        hello sir , im umme , i have downloaded ur code media player from android hives we have debugged the program but in the UI of player is showing me a rendering problem :”invalid drawable tag LinearLayout” and when i run the program it says the application have unfortunately stopped can u pls help me sir ….

      • Jay

        sure…thnx

  • Neelam singh chahal

    Just outstanding. To the point. Very useful resources. Simple and effective covering the most needed functions. Great

  • hussein kalash

    thank you very useful

  • Murat Püsküllüoğlu

    hi here is my question how i can modify to real time tracking on google maps and more than one gps signal

  • Hn Rakesh

    How to add that LocationFound activity in manifest!!!???

  • syed tanveer Hussain

    bundle of thanks…. but is there any way to center the search view in the action bar.

  • Akash ohal

    Thanks so much sir

  • Himanshi Puniya

    Sir please send a link to open a fragment on click of expendable list view child item in android studio.i have need this please send to my email “puniya844@gmail.com”.