Introduction
This article explains the Action Bar menu on Android. The sample application is developed using Android Studio.
The Action Bar is present at the top of an Activity in Android. It can display icon actions that can trigger additional views. It is also used in navigation within your application.
The Action Bar was introduced in version 3.0. You can use the Action Bar using the Sherlock Library on Android devices version 1.6. The activity populates the action bar in the onCreateoptionmenu() method. We define the action for the action bar inside the XML file. The MenuInflator class allows inflation of actions defined in an XML file and adds them to the ActionBar.
-
onCreateOptionMenu(): the method that is called only before the optionMenu is displayed.
-
getMenuInflator(): returns the MenuInflator
-
onoptionsItemSelected(): called when you click on a menu item and display what you want in your Activity.
In this, you will create an XML file that consists of an item that you want to show on the ActionBar.
- <menu xmlns:android="http://schemas.android.com/apk/res/android" >
-
- <item
- android:id="@+id/menuitem3"
- android:orderInCategory="10"
- android:showAsAction="ifRoom"
- android:icon="@drawable/images"
- android:title="Refresh"
- />
- <item
- android:id="@+id/action_settings"
- android:title="Settings">
- </item>
- </menu>
When you click on the menu item it will display a message on the Activity.
Step 1
Create the project like this:
Create another XML file for the menu item as in the following:
- <menu xmlns:android="http://schemas.android.com/apk/res/android" >
-
- <item
- android:id="@+id/menuitem3"
- android:orderInCategory="10"
- android:showAsAction="ifRoom"
- android:icon="@drawable/images"
- android:title="Refresh"
- />
- <item
- android:id="@+id/action_settings"
- android:title="Settings">
- </item>
- </menu>
Step 4
Create a Java class file and write this:
- package com.actionbar;
- import android.app.ActionBar;
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
- import android.view.MenuItem;
- import android.widget.Toast;
-
- 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) {
-
- getMenuInflater().inflate(R.menu.main, menu);
- return true;
- }
- @Override
- public boolean onOptionsItemSelected(MenuItem item) {
- switch (item.getItemId()) {
- case R.id.menuitem3:
- Toast.makeText(this, "Menu Item 1 selected", Toast.LENGTH_SHORT).show();
- break;
-
-
-
-
-
- default:
- break;
- }
-
- return true;
- }
-
- }