How to start with ActionBar in Android?

By | August 23, 2012

With Android 3.0 Google eliminated the need of hardware menu button which is replaced by Action Bars.

Here is a quick example on how to use ActionBars.

Action Bar in Android

First create a new project and name it ActionBarExample.

Now create a folder named “menu” in res folder and create a new XML file inside it named “action_bar_menu.xml”.

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/menuitem1" android:showAsAction="ifRoom" android:title="Test1"></item>
    <item android:id="@+id/menuitem2" android:showAsAction="ifRoom" android:title="Test2"></item>
</menu>

Now the java code for implementing this ActionBar.

MainActivity.java

package com.example.actionbarexample;

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 MainActivity extends Activity {
	@Override
	  public 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.action_bar_menu, menu);
	    return true;
	  }

	  @Override
	  public boolean    onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.menuitem1:
	      Toast.makeText(this, "Test 1 Clicked", Toast.LENGTH_SHORT).show();
	      break;
	    case R.id.menuitem2:
	      Toast.makeText(this, "Test 2 Clicked", Toast.LENGTH_SHORT).show();
	      break;

	    default:
	      break;
	    }

	    return true;
	  }
	} 

As there is enough space in the ActionBar otherwise you may see the Overflow menu or you have to use the Option menu button on your phone.

Please leave your comments om this post.

One thought on “How to start with ActionBar in Android?

  1. Pingback: How to start with ActionBar in Android? « Emerson Barros

Leave a Reply

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