Home » Android » Basics of Android Actionbar

Basics of Android Actionbar

Welcome to the first module of this series. In this tutorial we will learn about basics of android action bar, where can we use action bar and how to create basic action bar. Moving forward we will learn how to customize them and how to create grouped action bar.

Below are the topics that we will cover in this module:

  • What is action bar?
  • Where can we use it?
  • Basic action bar
  • Grouped action bar
  • Custom action bar
  • Gallery action bar

 

What is action bar?

Action bar is the UI component that is displayed at the top of your activity. It can be used to display application title, application icon and custom views too. You can also add action views in your action bar like search box. It can also be used to navigate between your application’s different views. Other than that it can also be used to create tabbed functionality in your application. Android SDK version 11 or higher supports the action bar.

 

Where can we use it?

Action bar can be used:

  • to display application icon, application title, subtitle.
  • to display action views like search box and custom views.
  • can be used to navigate between activities.
  • can be used in tabbed navigation by creating tabs.
  • and many other places.

So overall, action bar is one of the most important enhancements in Android, which can be used in many ways and can make your application interactive.

 

Basic action bar

Let’s start with creating basic action bar.

There are 2 main steps to have action bar functionality in your application.
1. Create xml layout under menu folder.

basic_action_bar_menu.xml:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
android:id="@+id/menuOption_Refresh"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_refresh"
android:title="Refresh">
</item>
<item
android:id="@+id/menuOption_Edit"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_edit"
android:title="Edit">
</item>
<item
android:id="@+id/menuOption_Add"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_person"
android:title="Add">
</item>

<item
android:id="@+id/menuOption_Delete"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_discard"
android:title="Delete">
</item>
<item
android:id="@+id/menuOption_Save"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_save"
android:title="Save">
</item>
<item
android:id="@+id/menuOption_Settings"
android:showAsAction="ifRoom|withText"
android:icon="@drawable/ic_action_settings"
android:title="Settings">
</item>
</menu>

In this xml file we have created 6 menu items and each item have same configuration, let’s go through each configuration.
android:id = ID of the item.
android:showAsAction = this property decides the appearance of menu items in action bar, which means when and how to display the item. Below are the value’s and their description (from android’s developer site):

ifRoom Only place this item in the Action Bar if there is room for it.
withText Also include the title text (defined by android:title) with the action item. You can include this value along with one of the others as a flag set, by separating them with a pipe |.
never Never place this item in the Action Bar.
always Always place this item in the Action Bar. Avoid using this unless it’s critical that the item always appear in the action bar. Setting multiple items to always appear as action items can result in them overlapping with other UI in the action bar.
collapseActionView The action view associated with this action item (as declared by android:actionLayout or android:actionViewClass) is collapsible.
Introduced in API Level 14.

Multiple values can be assigned  to showAsAction config separated by ” | “

android:icon = icon of that item
android:title = title of that icon

 

2. Add click functionality or other logic for action bar items in your activity.

BasicActionBarActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class BasicActionBarActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);
   setContentView(R.layout.action_bar_activity);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
   // TODO Auto-generated method stub
   MenuInflater inflater = getMenuInflater();
   inflater.inflate(R.menu.basic_action_bar_menu, menu);
   return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   // TODO Auto-generated method stub
   switch (item.getItemId()) {
      case R.id.menuOption_Edit:
        Toast.makeText(this, "Edit Menu Clicked", Toast.LENGTH_SHORT).show();
      break;
      case R.id.menuOption_Refresh:
        Toast.makeText(this, "Refresh Menu Clicked", Toast.LENGTH_SHORT).show();
      break;
      case R.id.menuOption_Add:
        Toast.makeText(this, "Add Menu Clicked", Toast.LENGTH_SHORT).show();
      break;
      case R.id.menuOption_Delete:
        Toast.makeText(this, "Delete Menu Clicked", Toast.LENGTH_SHORT).show();
      break;
      case R.id.menuOption_Save:
        Toast.makeText(this, "Save Menu Clicked", Toast.LENGTH_SHORT).show();
      break;
      case R.id.menuOption_Settings:
        Toast.makeText(this, "Settings Menu Clicked", Toast.LENGTH_SHORT).show();
      break;
      default:
      break;
   }
   return true;
 }
}

In above class I am overriding the activity’s onCreateOptionsMenu() method and in that I am inflating menu from basic_action_bar_menu.xml file by using inflate() method.
Next step is to override the onOptionsItemSelected() method and add click functionality. I am using switch statement to display the Toast message based on the clicked menu item.

That’s all we need to do to create very basic action bar in our application.
Below are the screenshots of how it would look like.

action_bar_1st_example 

action bar in Portrait mode

action_bar_1st_example_landscape

 

action bar in Landscape mode

1st screenshot shows the application in portrait mode. It is showing only 3 items in action bar, rest of the items can be seen by pressing hardware menu button.
2nd screenshot show the application in Landscape mode. It is showing 4 items in action bar with text aligned on the right of each item. The reason being, we have assigned “ifRoom” value to showAsAction config, so number of items will be shown based on the room available, in portrait mode there is enough space available to display 4 items with text, and in landscape there is room to display only 3 items.

 

Grouped action bar

Using android Action bar we can create Grouped menu items also, for example you can display contact specific options like Edit, Add and Delete.

grouped_action_bar.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
android:id="@+id/menuOption_Refresh"
android:icon="@drawable/ic_action_refresh"
android:showAsAction="ifRoom|withText"
android:title="Refresh">
</item>
<item
android:id="@+id/menuOption_Settings"
android:icon="@drawable/ic_action_settings"
android:showAsAction="ifRoom|withText"
android:title="Settings">
</item>
<item
android:id="@+id/menuOption_Contact"
android:icon="@drawable/ic_action_person"
android:showAsAction="always"
android:title="Contact">
<menu>
<item
android:id="@+id/menuOption_Edit"
android:icon="@drawable/ic_action_edit"
android:showAsAction="ifRoom|withText"
android:title="Edit">
</item>
<item
android:id="@+id/menuOption_Add"
android:icon="@drawable/ic_action_person"
android:showAsAction="ifRoom|withText"
android:title="Add">
</item>
<item
android:id="@+id/menuOption_Delete"
android:icon="@drawable/ic_action_discard"
android:showAsAction="ifRoom|withText"
android:title="Delete">
</item>
</menu>
</item>
</menu>

Above xml file has 3 menu items refresh, settings and contact; contact menu item has 3 more sub items called Edit, Add and Delete.
Below is the screenshot.

grouped_action_bar

 Grouped Action Bar

You must have noticed in the screenshot action items are aligned at the bottom of the screen. You can split the action bar and display it at the bottom of the screen by adding below config to activity tag:

android:uiOptions="splitActionBarWhenNarrow"

for example:

<activity android:name=”com.codeureka.actionbarexample.SplitActionBar” android:label=”@string/app_name” android:uiOptions=”splitActionBarWhenNarrow”> </activity>

Custom action bar

Android supports customizing the action bar at runtime, for example you can display different logo and title for different activities in same application.

CustomActionBar.java

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout.LayoutParams;

public class CustomActionBar extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);

   Button btnCustomActionBar = new Button(getApplicationContext());
   btnCustomActionBar.setText("Customize Action Bar");

   setContentView(btnCustomActionBar);
   LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
   btnCustomActionBar.setLayoutParams(params);

   btnCustomActionBar.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
      // TODO Auto-generated method stub
        ActionBar actionBar = getActionBar();
        actionBar.setLogo(R.drawable.ic_action_person);
        actionBar.setTitle("Action Bar");
        actionBar.setSubtitle("Customized Action Bar");
      }
   });
  }
}

In this example I have created one button called “Customize Action Bar”, the important part is the logic to customize the action bar on button click, let’s go through that part of code.

ActionBar actionBar = getActionBar();

We are creating an object of ActionBar class, getActionBar() will return the reference of activity’s action bar.

actionBar.setLogo(R.drawable.ic_action_person);
actionBar.setTitle(“Action Bar”);
actionBar.setSubtitle(“Customized Action Bar”);

Above three methods will set action bar’s logo, title and subTitle respectively.

custom_action_bar

 

Custom action Bar

Gallery action bar

Android provides a functionality to hide and show the action bar at runtime. For example gallery application, tapping on screen will hide the action bar; tapping again on screen will show the action bar.

To achieve this functionality you should use “HideActionBarTheme” for your activity. So add theme config in your AndroidManifest.xml file and assign it HideActionBarTheme.

<activity
android:name="com.codeureka.actionbarexample.GalleryActionBar"
android:label="@string/app_name"
android:theme="@style/HideActionBarTheme"
android:uiOptions="splitActionBarWhenNarrow">

Now in your activity class, write logic to hide and show the action bar on screen tap.

GalleryActionBar.java

import android.app.ActionBar;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.TextView;
import android.widget.FrameLayout.LayoutParams;

public class GalleryActionBar extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
   // TODO Auto-generated method stub
   super.onCreate(savedInstanceState);

   TextView textView = new TextView(getApplicationContext());
   textView.setText("Gallery Action Bar: This example shows the exact action bar behaviour as of android Gallery.");
   setContentView(textView);

   LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
   params.setMargins(15, 150, 5, 5);
   textView.setLayoutParams(params);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
   if(event.getAction() == MotionEvent.ACTION_DOWN){
      ActionBar actionBar = getActionBar();
      if (actionBar != null) {
        if(actionBar.isShowing())
          actionBar.hide();
        else
          actionBar.show();
        }
      }
      return true;
   }
}

In this example I am overriding onTouchEvent() method which will be called when user taps on the screen. In this method I am checking whether the activity has action bar or not, if yes and if it is visible; call hide() or else call show().

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>