August 23, 2012

How to start with ActionBar in Android?

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.

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”.


<?xml version="1.0" encoding="utf-8"?><menu xmlns: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.

package com.example.actionbarexample;import;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 {@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {MenuInflater inflater = getMenuInflater();inflater.inflate(, menu);return true;}@Overridepublic booleanonOptionsItemSelected(MenuItem item) {switch (item.getItemId()) {case, "Test 1 Clicked", Toast.LENGTH_SHORT).show();break;case, "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.

Website PinFacebook TwitterMyspaceFriendfeedTechnoratidel.icio.usDiggGoogleStumbleUponPremium Responsive

Leave a Reply Cancel reply