Android Menus and Action Bar

Learn how the Menus and Action Bar work in Android.
Android uses two different ways to display global actions which the user can select. They are

  1. Usage of Action Bar
  2. Usage of Menu

Usage of Action Bar

Action Bar is type of window feature at the top of the activity that display the following ones activity title, navigation modes, other interactive items and it identifies the application and user location. It also provides the user actions. The action bar offers users a uniform interface across applications and the system gracefully adapts the action bar’s appearance for different screen configurations. We can control the behaviors and visibility of the action bar by using action bar APIs.

We can add an action to the ActionBar icon and this icon appears in our application. We select this icon by using the onOptionsItemSelected() method will be called with the value android.R.id.home.  It returns to the main Activity in our program.

Eg: –

case android.R.id.home:
Intent intent = new Intent(this, OverviewActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;

We can create the menu programmatically or use pre-defined XML resources which we inflate through MenuInflator class. Each instances of class get accessed through the getMenuInflator() method. The onCreateOptionsMenu() method is only called once. We want to influence the menu later we use the onPrepareOptionsMenu() method.

ActionBar tabs

 

We can add tabs in the action bar by using fragments through the newTab() method. It uses two Fragments, called DetailFragment and ImageFragment

Eg: –

package com.android.fragment;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.ActionBar.TabListener;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// setup action bar for tabs
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
Tab tab = actionBar.newTab().setText("First tab").setTabListener(
new MyTabListener<DetailFragment>(this, "artist",
DetailFragment.class));
actionBar.addTab(tab);
tab = actionBar.newTab().setText("Second
Tab").setTabListener(new
MyTabListener<ImageFragment> (this,
"album",ImageFragment.class));
actionBar.addTab(tab);

}
public static class MyTabListener<T extends Fragment> implements
TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
/**
* Constructor used each time a new tab is created.
*
* @param activity
*            The host Activity, used to instantiate the fragment
* @param tag
*            The identifier tag for the fragment
* @param clz
*            The fragment's Class, used to instantiate the fragment
*/
public MyTabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
/* The following are each of the ActionBar.TabListener callbacks */
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.setCustomAnimations(android.R.animator.fade_in,
R.animator.animationtest);
ft.attach(mFragment);
}
}

public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
ft.setCustomAnimations(android.R.animator.fade_in,
R.animator.test);
ft.detach(mFragment);
}

}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
}
}

Custom Views in the ActionBar

We can add custom view to the ActionBar

Eg:-

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar = getActionBar();
actionBar.setCustomView(R.layout.actionbar_view);
actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
| ActionBar.DISPLAY_SHOW_HOME);
}

Action Bar provides various features. They are,

A)     Provide a dedicated space for identifying the application brand and user location:-

This can be done through the app icon or logo on the left side and the activity title. If the current view is identified by a navigation label, like currently selected tab we may choose to remove the activity title.

B)    Provide consistent navigation and view refinement across different applications:-

Action bar uses built-in tab navigation for switching between fragments and also it offers a drop down list.

C)    Make key actions for the activity like search, create, share etc are prominent and accessible to the user in a predictable way:-

We can specify instant access to key user actions by placing items from the options menu directly in the action bar, as “action items.” Action items can also gives an “action view,” which provides an embedded widget for even more immediate action behaviors. Menu items that are not promoted to an action item are available in the overflow menu, revealed by either the device Menu button (when available) or by an “overflow menu” button in the action bar (when the device does not include a Menu button)

Usage of Menu

The application opens a menu which shows additional actions through the popupmenu. Normally we specify our menu entries by the way of adding options in the action bar when the enough space is available in the action bar. Otherwise the remaining menu items are displayed in the popup menu. The option menu and the action bar of our activity is filled by the method onCreateOptionsMenu().

Context menus

Context menu is triggered when the user “long presses” the view. The registration of context menu for view through the registerForContextMenu(view) method. A context menu is activated as the context menu is discarded after its usage it called the onCreateContextMenu() method.  The Android platform may also add options to your View.

Eg:- EditText provides context options to select text, etc.

Menus and Action Bar

Here we are discussing how to create and evaluate an option which shows in the action bar if sufficient space is available.

Eg:- Create a project called “com.android.socialapp” with the Activity called “OverviewActivity”. Change the “main.xml” layout file in the diretory “/res/layout/” to the following:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
 <Button
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Preferences" >
</Button>

<Button
android:id="@+id/Button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change Preferences" >
</Button>

</LinearLayout>

Add a menu XML resource

Select your project, right click on it and select New → Other → Android → Android XML File to create a new XML resource.

Select the option “Menu”, enter as File “mainmenu.xml” and press the button “Finish”.

It will create a new file called “mainmenu.xml” in the folder “res/menu and android provide an editor to edit file. For open this editor we are using the following steps.

Right-click on your menu file and select Open with → Android Menu Editor.

Switch to the “Layout” tab of the editor, press Add and select “Item”. It maintain the following value and also define the menu entry and displayed in the action bar if there is sufficient space available.

Android Main Menu
Android Main Menu

Change the Activity class “OverviewActivity” to the following. The OnCreateOptionsMenu method helps to create the menu. The “onOptionsItemSelected”

Behavior is currently hard-coded to show a Toast and will soon call the preference settings. We have to disable or hide the menu by using “onPrepareOptionsMenu” this method.

Eg:-

package com.android.socialapp;
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 OverviewActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
Toast.makeText(this, "Just a test", Toast.LENGTH_SHORT).show();
return true;
}
}

Run our application the item is displayed. If we want more item select the “Menu” on the emulator and we should see a small info message.

Using a menu resource is a good practice for a few reasons:

  1. It’s easier to visualize the menu structure in XML.
  2. It separates the content for the menu from your application’s behavioral code.
  3. It allows you to create alternative menu configurations for different platform versions, screen sizes, and other configurations by leveraging the app resources framework.