0% found this document useful (0 votes)
101 views52 pages

Mad Unit 5 (A)

Menus in Android allow users to access actions and options. There are three types of menus: options menus displayed via the device menu button, submenus that provide more specific options, and context menus accessed by long pressing. Menus are defined in XML files and inflated in activities. Options menus can be created by overriding onCreateOptionsMenu() and handling selections in onOptionsItemSelected(). Menu items, their text, icons, and IDs are defined in XML. When an item is selected, its ID is retrieved and the appropriate action is taken, like updating a text view.

Uploaded by

varsha reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views52 pages

Mad Unit 5 (A)

Menus in Android allow users to access actions and options. There are three types of menus: options menus displayed via the device menu button, submenus that provide more specific options, and context menus accessed by long pressing. Menus are defined in XML files and inflated in activities. Options menus can be created by overriding onCreateOptionsMenu() and handling selections in onOptionsItemSelected(). Menu items, their text, icons, and IDs are defined in XML. When an item is selected, its ID is retrieved and the appropriate action is taken, like updating a text view.

Uploaded by

varsha reddy
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

IV.

BTECH I-SEM, CSE: MOBILE APPLICATION DEVELOPMENT


UNIT- V(A)
CREATING INTERACTIVE MENUS AND ACTIONBARS

Menus and Their Types:


 Android SDK supports three types of menus: Options, Submenu, and Context, as detailed in the
following list:
 Options Menu — Also known as the Activity menu, this menu is displayed when a MENU button

is clicked. In an options Menu, the menu items are displayed in the form of text, check box, or
radio buttons. there were two types of Options Menus:
1. Icon Menu — The icon Menu appears when the user presses the MENU button on the device.
The menu items in the icon Menu can display icons as well as text. The icon Menu does not
display check boxes, radio buttons, or the shortcut keys for menu items.
2. Expanded Menu — If the menu has more than six menu items, the first five items are
displayed as an icon Menu and the sixth option appears as a More button. Clicking the More
buttons displays the Expanded Menu. The Expanded Menu can display menu items in the
form of text, check boxes, or radio buttons.
 Submenu — Submenu refers to the menu that displays more detailed or specific menu options
when a menu item is selected. Each menu option is displayed with its full text, check box, radio
button, and shortcut key. Icons are not displayed in the submenu options. Android does not
support nested submenus.
 Context Menu — The context Menu is displayed when we tap-and-hold on the concerned view
or when a user holds the middle D-pad button. Context Menus support submenus, check boxes,
radio buttons, and shortcuts, but we cannot display icons in a Context Menu.

Creating Menus through XML:


 We can define a menu in the form of an XML file, which is then loaded by the Android SDK. As
usual, Android generates resource IDS for each of the loaded menu items.
 The XML file for the menu has to be kept in a specific, designated folder that does not exist by
default; we need to create it manually.
 Let’s create a new Android application called MenuApp. We see that a folder called menu already
exists in our res/ directory. The menu folder also contains a file activity_menu_app.xml by default.

Creating an Options Menu:


 An Options Menu is menu displayed when MENU button on device is clicked. An options Menu is
defined through an XML file in the res/menu folder of the application. Automatically created
activity_menu_app.xml file contains the following data

P.SEKHAR
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings"
android:title="@string/menu_settings"
android:orderInCategory="100"
android:showAsAction="never" />
</menu>
 We see that the root node of our menu in the XML file is <menu>. The default menu item with the
ID menu_settings shows text that is defined in the strings.xml file. Let's define certain <item> nodes
to display certain menu items. The code written in activity_menu_app.xml file is as shown below
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create Database"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/list_rows"
android:title="List Rows" />
<item android:id= "@+id/search_row"
android:title="Search"
android:icon="@drawable/ic_launcher"/>
<item android:id="@+id/delete_row"
android:title="Delete" />
<item android:id="@+id/update_row"
android:title="Update"
android:icon="@drawable/ic_launcher" />
</menu>
 We see that we have defined six menu items in the preceding menu, and a unique ID is assigned to
each of them. The android:titie and android:icon attribute defines text and icon for the menu item.
 The menu items defined in our menu file are create Database, Insert Rows, List Rows, Search,
Delete, and Update. The Six menu items are assigned the IDs as create_database, insert_rows,
list_rows, search_row, delete_row, and update_row.
 In the application, we want to display a message that asks the user to select the MENU button on the
device or emulator for displaying the icon Menu. We use the TextView control to display messages.
 To define TextView, we write the code as shown below in the layout file activity_menu_app.xml.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
</LinearLayout>
 We added a TextView with the ID selectedopt, we use that to display desired text messages to user.
The TextView also is used to inform which menu item is selected by the user.
 To inflate or merge the menu that we defined in the mymenu.xml file in our application and also to
inform which menu item is selected by user, we write Java code as shown below in java activity file.
package com.androidunleashed.menuapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
public class MenuAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_app);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R.id.insert_rows:
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R.id.search_row:
selectedOpt.setText("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R.id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
}
return true;
}
}
 We capture TextView defined in layout and assign it to a TextView object named selectedOpt and
use TextView for displaying initial message and for informing which menu item is selected by user.
 The onCreateOptionsMenu() method of the Activity is called when the user clicks the MENU button
of the device. So, we override this method to display our icon Menu.
 To display our icon Menu, we need to inflate or merge our menu that we defined in the
activity_menu_app.xml file in the menu provided as a parameter to this method.
 To inflate menu in activity_menu_app.xml file, we get MenuInflater from Activity class. An object,
inflater, is created of MenuInflater class and inflater's inflate method is called to inflate, or merge,
our own menu defined in activity_menu_app.xml file to menu given as a parameter to this method.
 The onCreateOptionsMenu() method is set to return Boolean value true to allow Android to display
menu. The next step for us is to define action to take place when the user selects any of menu items.

Handling Menu Selections:


 All menu items selected in Activity's menu are handled through onOptionsItemSelected() method.
The selected menu item is passed to this method as the MenuItem parameter. We override this
method in the Activity to write the code that we want to execute when a menu item is selected.
 In method, we extract Menu item ID of the menu item selected for identifying it and then can take
respective action. getItemId() method helps in knowing ID of selected menu item. The following
code explains how action is taken when a menu item is selected:
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
………….………………….
……………………………..
}
return true;
}
 The preceding method selected menu item is passed to this method and assigned to the Menuitem
object item. getItemId() method is called to know the ID of the selected menu item, and through the
switch statement respective action is taken on the selected menu item.
 In this code, we are setting a text message through the TextView object selectedOpt to inform the
user which of the menu items is selected. On running the application, we get output as shown below

Defining Check Boxes and Shortcuts:


 Here we add more menu items to the menu in our application MenuApp. One of the newly added
menu items will be checkable, and the other will be invoked with assigned shortcut keys. The menu
file activity_menu_app.xml is modified to appear as shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create Database"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/list_rows"
android:title="List Rows" />
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/ic_launcher"/>
<item android:id= "@+id/delete_row"
android:title="Delete" />
<item android:id="@+id/update_row"
android:title ="Update"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/sort_rows"
android:title="Sort Table"
android:checkable="true"
android:checked="true" />
<item android:id="@+id/merge_row"
android:title="Merge Rows"
android:alphabeticShortcut="m"
android:numericShortcut="4"/>
</menu>

 We see that the code now has eight menu items. The seventh menu item, sort_rows, is set to appear
in the form of a check box via the android:checkable attribute. When we set the value of the android
checkable property to true, the menu item appears as a check box.
 The check box can be initially set to appear in either a checked or unchecked state by the
android:checked attribute, when we set android:checked="true", the menu item appears as checked
by default.
 Shortcut keys are assigned to the last menu item, Merge ROWS (merge_row). When we set the
android:aiphabeticshortcut="m" attribute, shortcut key m for full keyboard is assigned to menu item.
 Similarly, the android:numericshortcut="4" attribute assigns the shortcut key 4 from the numeric
keypad. The shortcut keys are displayed below the menu item text.
 When the menu is open (or while holding the MENU key), if we press the m key from the full
keyboard or 4 from the numeric keypad, the menu item Merge Rows is selected.On running the
application, we get output as shown below
Adding Submenus:
 A submenu is a collection of menu items invoked when a regular menu item is selected. Usually, a
submenu represents more detailed options for the selected menu item. The submenu can be
associated with any menu item.
 A submenu is created by enclosing <item> nodes within the <menu> node, where <item> nodes
represent the submenu options and the <menu> node acts as the root node of the submenu.
 To associate a submenu with any menu item, just put the <menu> node of the submenu along with
its nested <item> nodes inside <item> node of menu item to which we want to assign the submenu.
 Let's add a submenu consisting of three menu items—search on code, search on Name, and search on
Price to the Search menu. To add a submenu modify activity_menu_app.xml as shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create Database"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/insert_rows"
android:title="Insert Rows"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/list_rows"
android:title="List Rows" />
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/ic_launcher">
<menu>
<group android:checkableBehavior="single">
<item android:id="@+id/search_code"
android:title="Search on Code"
android:checked="true" />
<item android:id="@+id/search_name"
android:title="Search on Name"
android:alphabeticShortcut="n"
android:numericShortcut="6" />
<item android:id="@+id/search_price"
android:title="Search on Price" />
</group>
</menu>
</item>
<item android:id= "@+id/delete_row"
android:title="Delete" />
<item android:id="@+id/update_row"
android:title ="Update"
android:icon="@drawable/ic_launcher" />
<item android:id="@+id/sort_rows"
android:title="Sort Table"
android:checkable="true"
android:checked="true" />
<item android:id="@+id/merge_row"
android:title="Merge Rows"
android:alphabeticShortcut="m"
android:numericShortcut="4"/>
</menu>
 We can see that a submenu has been created, consisting of three menu items, search on Code, Search
on Name, and Search on Price, With IDs search_code, search_name, and search_price. Submenu is
assigned to search menu item by nesting <menu> node within <item> node of the search menu item.
 If we want menu items to appear as radio buttons, we need to nest them within <group> node. The
<group> node is used to collect certain nodes and for applying attributes to all the nested nodes.
 The android:checkableBehavior attribute determines whether to make menu items nested within the
<group> node appear as radio buttons, check boxes, or simple menu items. The attribute can take
three values:
1. single — Only one item can be checked at a time, producing radio buttons.
2. All — Any item can be checked, producing check boxes.
3. None — The item appears as simple text, without a check box or radio button.
 We have defined an Expanded Menu and a submenu for the search menu item of our icon Menu with
the menu file mymenu.xml. Next, we add statements to onOptionsItemSelected() method.
 These statements display messages showing which menu item from the Expanded Menu or submenu
has been selected. The Activity file appears as shown below.
package com.androidunieashed.menuapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
public class MenuAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater ();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
©Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R. id. insert_rows :
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R. id. search_row:
selectedOpt. setText ("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R.id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
case R.id.sort_rows:
selectedOpt.setText("You have selected Sort Table option");
item.setChecked(!item.isChecked());
break;
case R.id.merge_row:
selectedOpt.setText("You have selected Merge Rows option");
break;
case R.id.search_code:
selectedOpt.setText ("You have selected Search on Code option");
break;
case R.id.search_name:
selectedOpt.setText("You have selected search on Name option");
break;
case R.id.search_price:
selectedOpt.setText("You have selected Search on Price option");
break;
}
return true;
}
}

 When the application is run, we see a TextView prompting us to select a MENU button, after which the
icon Menu is displayed. After we select the search menu item from the icon Menu, the search
submenu is displayed.
 We can select a menu item from the submenu by either clicking it or using its shortcut key (if any).
For example, if we select search on code as shown, the TextView responds showing the message,
You have selected Search on Code option, as shown below.

P.SEKHAR 10
Creating a Context Menu:
 A context menu appears as a floating window and is displayed when the user taps and holds on
widget, holds the middle D-pad button, or presses the trackball. An Activity can have only a single
options menu but many context menus. Context menus are removed from memory when closed.
 Let's define two context menus that we associate with two different TextView controls. For each
context menu, we need to add a separate file to the menu folder of our project. Right-click on the
res/menu folder and add two XML files called mycontext_menu1.xml and mycontext_menu2.xml.
 Let's define three menu items cut, copy, and Find in the first context menu. The code in
mycontext_menu1.xml is shown in below.
<?xml version="l.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="all">
<item android:id="@+id/cut_item"
android:title="Cut" />
<item android:id="@+id/copy_item"
android:title="Copy" />
</group>
<item android:id="®+id/find_item"
android:title="Find">
<menu>
<item android:id="®+id/find_next"
android:title="Find Next" />
</menu>
</item>
</menu>
 The first two items are are set to appear as check boxes by nesting them within the <group> node
and applying the android: checkabieBehavior attribute to them. A submenu consisting of a single
menu item, Find Next (Find), is attached to the third menu item.
 Let's define two menu items in the second context menu. The menu file of the second context menu,
mycontext_menu2 .xml, appears as shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/open_item"
android:title="Open"
android:alphabeticShortcut="o"
android:numericShortcut="5" />
<item android:id="@+id/close_item"
android:title="Close"
android:checkable="true" />
</menu>
 This context menu consists of two menu items titled open and close. To invoke the open menu item,
the shortcut keys O (full keyboard) and 5 (numeric keypad) can be used.
 The second menu item, close, is set to appear as a check box by setting the android:checkable
attribute to true. If we want to assign 2 context menus to 2 TextView controls so that the respective
context menu appears when we press and hold a TextView control, we have to write some code.
 Let's modify layout file activity_menu_app.xml to add these 2 TextView controls, as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
<TextView
android:text="View to invoke first context menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/contxtl_view" />
<Textview
android:text="view to invoke second context menu"
android:layout_width="match_parent"
android:layout_height="wrapcontent"
android:id="@+id/contxt2_view"/>
</LinearLayout>
 We see that two TextView controls were initialized to two views to invoke first and second context
menu.The IDs assigned to these TextView controls are contxt1_view and contxt2_view.
 Next, we need to write some Java code into MenuAppActivity.java. To create context menus, we
need to override the oncreateContextMenu method for registering views that are supposed to use it.
 The option to register a context menu to view(s) enables us to associate context menus for certain
selected views. A context menu is registered to a view through registerForContextMenuO method
as shown in the following code:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
TextView contxt1View=(TextView)findViewById(R.id.contxtl_view);
TextView contxt2View=(TextView)findViewById(R.id.contxt2_view);
registerForContextMenu(contxt1View);
registerForContextMenu(contxt2View);
}
 We see that two TextView controls with the contxt1_view and contxt2_view IDs are captured from
layout file and mapped to the TextView objects contxt1view and contxt2View.
 The two TextView objects are passed to the registerForContextMenu () method, as we want to
associate them with the two context menus. Once a view is registered, onCreatecontextMenu()
method is invoked whenever we tap and hold on the registered view.
 The method also receives a Menu object as a parameter that we use to add menu items to it. To add
menu items to a menu, the add() method is used. We need to override the onCreateContextMenu ()
method for displaying the context menu.
 The method receives the menu object as a parameter to which we add the menu items for the context
menu. Besides the menu object, the method also receives the view object that initiated the context
menu and a contextMenuInfo object.
 ContextMenuInfo is an interface that belongs to ContextMenu and acts as an adapter for passing any
other information about menu inflation. onCreateContextMenu() method appears as shown here:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.contxtl_view)
{ MenuInflater inflater =
getMenuInflater();
inflater.inflate(R.menu.mycontext_menu1, menu);
menu.setHeaderTitle("Sample Context Menul");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
if (v.getId()==R.id.contxt2_view)
{ MenuInflater inflater =
getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2, menu);
menu.setHeaderTitle("Sample Context Menu2");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
}
 We see that we first identify which view has initiated the context menu, and accordingly we inflate
or merge the menu that we defined in mycontext_menu1.xml or mycontext_menu2.xml in the menu
provided as the parameter to the onCreateContextMenu () method.
 A MenuInflater class object, inflater, is created and its inflate method is invoked to inflate, or merge,
our own menu, defined in the respective XML file, with the menu parameter of this method.
 Two context menus are being created then title and icon are set to appear in the context menu's
header bar via setHeaderTitle and setHeaderIcon.

Handling context Menu Selections:


 The preferred approach to handling menu items selected in context menus is to override the
onContextItemSelected() method in the Activity. The menu item that is selected is passed to the
method as a parameter, as shown in the following code:
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case R.id.cut_item:
selectedOpt.setText("You have selected the Cut option");
item.setChecked(!item.isChecked()) ;
break;
............
............
}
return true;
}
 The Menu item ID of the selected menu item is extracted through the getItemId() method, and
accordingly message is displayed through TextView to display which context menu item is selected.
 We toggle the state of the checkable item through the MenuItem.isChecked() method. The method
returns true if the menu item is checked; otherwise it returns false.
 We change the state of menu item by passing a Boolean value that represents reverse of existing state.
The MenuAppActivity.java appears as shown below.
package com.androidunleashed.MenuApp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.ContextMenu;
public class MenuAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
setContentView(R.layout.main);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
TextView contxt1View=(TextView)findViewById(R.id.contxtl_view);
TextView contxt2View=(TextView)findViewById(R.id.contxt2_view);
registerForContextMenu(contxt1View);
registerForContextMenu(contxt2View);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R.id.insert_rows:
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R. id.search_row:
selectedOpt.setText("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R. id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
case R.id.sort_rows:
selectedOpt.setText("You have selected Sort Table option");
item.setChecked(!item.isChecked());
break;
case R.id.merge_row:
selectedOpt.setText("You have selected Merge Rows option");
break;
case R.id.search_code:
selectedOpt.setText("You have selected Search on Code option");
break;
case R.id.search_name:
selectedOpt.setText("You have selected Search on Name option");
break;
case R.id.search_price:
selectedOpt.setText("You have selected Search on Price option");
break;
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menulnfo)
{
super.onCreateContextMenu(menu, v, menulnfo);
if (v.getId()==R.id.contxtl_view)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menul, menu);
menu.setHeaderTitle("Sample Context Menul");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
if (v.getId()==R.id.contxt2_view)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2, menu);
menu.setHeaderTitle("Sample Context Menu2");
menu.setHeaderIcon(R.drawable.ic_launcher);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.cut_item:
selectedOpt.setText("You have selected the Cut option");
item.setChecked(!item.isChecked());
break;
case R.id.copy_item:
selectedOpt.setText("You have selected the Copy option");
item.setChecked(!item.isChecked());
break;
case R.id.find_item:
selectedOpt.setText("You have selected the Find Submenu");
break;
case R.id.findnext:
selectedOpt.setText("You have selected the Find Next option");
break;
case R.id.openitem:
selectedOpt.setText("You have selected the Open option");
break;
case R.id.close_item:
selectedOpt.setText("You have selected the Close option");
item.setChecked(!item.isChecked());
break;
}
return true;
}
}
 On running the application, we get outputs as shown below.
Creating Menus through Coding:
 In this section, we learn to create the three types of menus, options Menu, Submenu, and Context
Menu, with Java coding.

Defining Options Menus


 To define an options or Activity menu, we override the onCreateOptionsMenu method in the Java
Activity file MenuAppcodeActivity.java. The method receives a menu object as a parameter, which
is used to add menu items to it. To add menu items to the menu object, the add() method is used.
syntax: add (Group ID, Menu Item ID, Sort order ID, Menu text)
 The add () method requires following four parameters:
1. Group ID—An integer used for grouping a collection of menu items.
2. Menu item ID—A unique identifier assigned to each menu item to identify it. We can also use
the Menu.FIRST static constant and simply increment that value for successive menu items.
3. Sort order ID—Defines the order in which the menu items are to be displayed.
4. Menu text—Text to appear in the menu item.
 The group ID, Menu item ID, and sort order ID parameters in the add() method are all optional, and
we can use Menu.NONE in place of them. The following code adds a single menu item, Create
Database, to the Options Menu:
private static final int CREATE_DATAB = Menu.FIRST;
menu.add(0,CREATE_DATAB,0,"Create Database").setIcon(R.drawable.ic_launcher);
 We see that the CREATE_DATAB is assigned a static constant, Menu.FIRST, and is used as a Menu
Item ID in the add() method. In the add() method, we can see that Group ID is assigned the value 0
 All the menu items that we want to be a part of this group are assigned the Group ID of 0. The
CREATE_DATAB is assigned to Menu item ID; the sort order ID is 0; and the string create Database
is the menu item text.
 The setIcon() method assigns the ic_launcher.png image to the menu item from the drawable
resource.

Assigning Icons:
 We can assign icons to the menu items in the Icon Menu using setIcon() method. Where icon file
name is a drawable resource identifier for the icon to be assigned to the menu item.
syntax: menuitem.setIcon(R.drawable.icon_filename);

Creating Submenus
 Submenus appear as single floating windows displaying all of their menu items. A submenu is
attached to a regular menu item that, when selected, invokes the submenu, hence displaying all the
menu items in it.
 A submenu is added through addSubMenu0 method. It supports same parameters as add() method
used to add menu items in Options Menu: Group ID, Menu Item ID, Sort order ID, and Menu Text.
 We can also use the setHeadericon method to specify an icon to display in the submenu's header bar
and the seticon () method to display the icon for the menu item to which this submenu is associated.
 The following code adds a submenu to a regular menu item, search:

private static final int SEARCH_ROW = Menu.FIRST + 3;


SubMenu searchSub = menu.addSubMenu(0, SEARCH_ROW, 3, "Search");
searchSub. setHeadericon (R.drawable. ic_launcher) ;
searchSub.setIcon(R.drawable.iclauncher);
searchSub.add(1, SEARCH_CODE, Menu.NONE, "Search on Code");

 We see that a submenu called searchSub is created for the regular menu item search. The menu item
search to which the submenu searchSub is associated is assigned a group ID of 0.
 SEARCH_ROW, which is assigned the value of the static constant Menu.FiRST+3, is assigned as the
Menu item ID; 3 is assigned as the sort order ID; and Search is assigned as the menu item text.
 The ic_iauncher.png file in Resources is set to display in the submenu's header bar. The image
ic_iauncher.png is set to display as an icon in the search menu item, to which the submenu searchsub
is associated. A menu item, search on code, is added to submenu through add() method.

Using Check Boxes/Radio Buttons in Menus:


 Android supports check boxes and radio buttons in menu items. To set a menu item as a check box,
we use the setcheckable() method.
syntax: setcheckabie(boolean);
 The menu item appears as a check box when the Boolean value true is passed to the setcheckable()
method. The following code makes a menu item appear as a check box:

menu.add(3, CLOSE_ITEM, Menu.NONE, "Close").setcheckable(true);

 By default, the check box is unchecked. To make the check box checked by default, we use the
setchecked() method. By passing the Boolean value true to the setchecked() method, we can make
the check box appear checked by default.
 The following code makes a menu item appear as a checked check box by default:

menu.add(3, CLOSE_ITEM, Menu.NONE,"Close").setcheckabie(true).setchecked(true);

 Radio buttons are mutually exclusive menu items displayed as a circles; only one menu item can be
selected in a group at any time. To create radio buttons, we need to make them part of the same
group. We assign the same group identifier to all of them; then we call setGroupcheckable() method.
syntax:
setGroupCheckabie(int GroupID, boolean Checkable, boolean Exclusive)

P.SEKHAR 20
 Where the GroupID refers to the group whose menu items we want to appear as radio buttons or
check boxes. The second parameter, checkable, should be set to true to make the check box or radio
button appear as checkable. If we pass a false value to the checkable parameter, then the menu items
appear neither as check boxes nor radio buttons.
 The third parameter, Exclusive, determines whether we want the menu items to be mutually
exclusive. If the Exclusive parameter is set to true, only one can be selected at a time. So we set the
parameter Exclusive to true if we want the menu items to appear as radio buttons. Passing the value
false to the Exclusive parameter makes all the menu items in the group appear as check boxes.
 The following code makes all the menu items of a submenu appear as radio buttons:

SubMenu searchSub = menu.addSubMenu(0, SEARCH_ROW, 3, "Search");


searchSub.add(1, SEARCH_CODE, Menu.NONE, "Search on Code").setChecked(true);
searchSub.add(1, SEARCH_NAME, Menu.NONE, "Search on Name");
searchSub.add(1, SEARCH_PRICE, Menu.NONE, "Search on Price");
searchSub.setGroupCheckable(1, true, true);

 We see that submenu called searchSub is created and associated with menu item, search. searchSub
submenu contains three menu items: search on code, Search on Name, and Search on Price.
 All three menu items are assigned the Group ID 1. All the menu items appear as checkable radio
buttons, because the checkable and Exclusive parameters in the setGroupCheckable () method are
passed as true.
 The first menu item in the group, search on Code, is set to appear as checked by default by passing
the value true to the setchecked() method.

Assigning Shortcut Keys


 The methods used to assign shortcut keys are setshortcut, setAlphabeticShortcut, and
setNumericshortcut.
1. In setshortcut() method, we can assign two shortcut keys. One of shortcut keys is used with
numeric keypad and second with the full keyboard. Neither key is case sensitive.
Example:

menu.add(0,MERGE_ROW,7,"Merge Rows").setShortcut('4', 'm');


This code assigns shortcut keys for both modes to the menu item Merge Rows. The number 4 is
used as the numeric keypad shortcut, and m acts as the shortcut key while using full keyboard.
This shortcut key also is displayed below the menu item text.

2. The setAlphabeticShortcut() and setNumericshortcut() methods can be used to define shortcut


keys for the numeric keypad and full keyboard separately, as shown here:

menu.add(0,MERGE_R0W,7,"Merge Rows").setAlphabeticShortcut('m').setNumericShortcut ('4');


Trying It Out
 Create a new Android project called MenuAppCode. We want to display three Text view controls in
the menu The first TextView directs the user to click the MENU button to display the menu. The
second and third TextView controls are used for displaying context Menus.
 When user taps and holds on either TextView control, a context Menu appears on screen. To display
three TextView controls, modify layout file activity_menu_app_code.xml to appear as shown below
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="®+id/selectedopt"/>
<TextView
android:text="View to invoke first context menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="®+id/contxtl_view" />
<TextView
android:text="View to invoke second context menu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/contxt2_view"/>
</LinearLayout>
 In the code, we can see that three TextView controls are assigned the IDs seiectedopt, contxti_view,
and contxt2_view. To tell user which views are meant for displaying context Menus, the TextView
controls are set to display text Views to invoke first and second context menu.
 To display the menu items in the Options menu, submenu, and context Menu, the Activity file
MenuAppcodeActivity.java is modified as shown below.
package com.androidunleashed.menuappcode;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.view.SubMenu;
import android.view.View;
import android.view.ContextMenu;
public class MenuAppCodeActivity extends Activity {
private static final int CREATE_DATAB= Menu.FIRST;
private static final int INSERT_ROWS = Menu.FIRST+1;
private static final int LIST_R0WS = Menu.FIRST+2 ;
private static final int SEARCH_ROW =Menu.FIRST+3;
private static final int DELETE_R0W =Menu.FIRST+4;
private static final int UPDATE_ROW =Menu.FIRST+5;
private static final int S0RT_R0WS = Menu.FIRST+6;
private static final int MERGE_R0W = Menu.FIRST+7;
private static final int SEARCH_C0DE = Menu.FIRST+8;
private static final int SEARCH_NAME = Menu.FIRST+9;
private static final int SEARCH_PRICE = Menu.FIRST+10;
private static final int CUT_ITEM = Menu.FIRST+11;
private static final int COPY_ITEM = Menu.FIRST+12;
private static final int OPEN_ITEM = Menu.FIRST+13;
private static final int CLOSE_ITEM = Menu.FIRST+14;
private static final int FIND_ITEM = Menu.FIRST+15;
private static final int FIND_NEXT = Menu.FIRST+16;
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_app_code);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
selectedOpt.setText("Please select MENU button to display menu");
TextView contxt1View=(TextView)findViewById(R.id.contxt1_view);
TextView contxt2View=(TextView)findViewById(R.id.contxt2_view);
registerForContextMenu(contxt1View);
registerForContextMenu(contxt2View);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0,CREATE_DATAB,0,"Create
Database").setIcon(R.drawable.ic_launcher);
menu.add(0,INSERT_ROWS,1, "Insert Rows").setIcon(R.drawable.ic_launcher);
menu.add(0,LIST_ROWS,2,"List Rows");
SubMenu searchSub = menu.addSubMenu(0, SEARCH_ROW, 3, "Search");
menu.add(0,DELETE_ROW,4,"Delete"); menu. add (0, UPDATE_ROW, 5,
"Update") ;
menu.add(0,SORT_ROWS,S,"Sort Table").setCheckable(true).setChecked(true);
menu.add(0,MERGE_ROW,7,"Merge
Rows").setAlphabeticShortcut('m').setNumericShortcut ('4') ;
searchSub.setHeaderIcon(R.drawable.ic_launcher);
searchSub.setIcon(R.drawable.ic_launcher);
searchSub.add(1, SEARCH_CODE, Menu.NONE, "Search on
Code").setChecked(true);
searchSub.add(1, SEARCH_NAME, Menu.NONE, "Search on
Name").setShortcut('6','n');
searchSub.add(1, SEARCH_PRICE, Menu.NONE, "Search on Price");
searchSub.setGroupCheckable(1, true, true);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId() ) {
case CREATE_DATAB:
selectedOpt.setText("You have selected Create Database option");
break;
case INSERT_ROWS:
selectedOpt.setText("You have selected Insert Rows option");
break;
case LIST_ROWS:
selectedOpt.setText("You have selected List Rows option");
break;
case SEARCH_ROW:
selectedOpt.setText("You have selected Search Submenu option");
break;
case DELETE_ROW:
selectedOpt.setText("You have selected Delete Row option");
break;
case UPDATE_ROW:
selectedOpt.setText("You have selected Update Row option");
break;
case SORT_ROWS:
selectedOpt.setText("You have selected Sort Table option");
item.setChecked(!item.isChecked());
break;
case MERGE_ROW:
selectedOpt.setText("You have selected Merge Rows option");
break;
case SEARCH_CODE:
selectedOpt.setText("You have selected Search on Code option");
break;
case SEARCH_NAME:
selectedOpt.setText("You have selected Search on Name option");
break;
case SEARCH_PRICE:
selectedOpt.setText("You have selected Search on Price option");
}
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.contxt1_view)
{ menu.setHeaderTitle("Sample Context Menul");
menu.setHeaderIcon(R.drawable.ic_launcher);
menu. add (2, CUT_ITEM, Menu.NONE, "Cut") ;
menu.add(2, COPY_ITEM, Menu.NONE, "Copy");
menu.setGroupCheckable(2, true, false);
SubMenu subcont = menu.addSubMenu(2, FIND_ITEM, Menu.NONE, "Find");
subcont.add(3, FIND_NEXT, Menu.NONE, "Find Next");
}
if (v.getId()==R.id.contxt2_view)
{ menu.setHeaderTitle("Sample Context
Menu2");
menu.setHeaderIcon(R.drawable.ic_launcher);
menu.add(3, OPEN_ITEM, Menu.NONE, "Open").setShortcut('S’,'o');
menu.add(3, CLOSE_ITEM, Menu.NONE, "Close").setCheckable(true);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CUT_ITEM:
selectedOpt.setText("You have selected the Cut option");
item.setChecked(!item.isChecked() ) ;
break;
case COPY_ITEM:
selectedOpt.setText("You have selected the Copy option");
item.setChecked(!item.isChecked()) ;
break;
case FIND_ITEM:
selectedOpt.setText("You have selected the Find Submenu");
break;
case FIND_NEXT:
selectedOpt.setText("You have selected the Find Next option");
break;
case OPEN_ITEM:
selectedOpt.setText("You have selected the Open option");
break;
case CLOSE_ITEM:
selectedOpt.setText("You have selected the Close option");
item.setChecked (!item.isChecked()) ;
break;
}
return true;
} }
 We see that the TextView with the ID seiectedopt is accessed from the layout file and is mapped to
TextView object seiectedopt. It is set to display text Please select MENU button to display menu.
 Two TextView controls with IDS context1_ view and contxt2_view are registered for displaying a
context Menu. The onCreateOptionsMenu() method defines the menu items for the options Menu as
well as for the search subMenu.
 The menu items defined for the options Menu are create Database, Insert Rows, List Rows, Delete,
Update, Sort Table, and Merge Rows. The menu items defined for the Search SubMenu are Search
on Code, Search on Name, and search on price.
 Shortcut keys are assigned for the Merge ROWS menu item and the Search on Name menu item of
the Search SubMenu. The Sort Table menu item is set as a checkable menu item. All the menu items
of the search SubMenu are set to appear as radio buttons.
 The onOptionsitemSelected () method informs the menu item that is selected by the user. It displays
text message through TextView seiectedopt to inform which of menu options is selected by user.
 The onCreateContextMenu() method displays the two context Menus. When the user taps and holds
on any of the TextView controls with the IDs context1_view and contxt2_view the method displays
the corresponding context Menu on the screen.
 The onContextItemSeiected() method does the job of informing us which menu item of the context
Menu is selected by the user. The output of this application is the same as above application

Applying a Context Menu to a ListView:


 To apply context Menus to ListView controls, let's create a new Android application called
contextMenuApp. To display the context Menu for the item selected from the ListView, let's add
Context Menu files to the menu folder.
 Right-click on the res/menu folder in the Package Explorer window and select the New, Android
XML File option. Enter the filename as mycontext_menu1. Keeping the Root Element: as menu,
click the Finish button to create the context file mycontext_ menu1.xml.
 Repeat the procedure to add one more context file called mycontext_menu2.xml to our menu folder.
Write the code as shown below in the mycontext_menu1.xml file.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/cut_item"
android:title="Cut" />
<item android:id="@+id/copy_item"
android:title="Copy" />
</menu>
 The code in the second context menu file, mycontext_menu2.xml, appears as shown below.
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="®+id/open_item"
android:title="Open" />
<item android:id="®+id/close_item"
android:title="Close" />
</menu>
 We want to display a TextView and a ListView in our application. The TextView directs the user to
take a desired action and tells the user which item from the ListView is selected by the user.
 The ListView control is used to display different items on the screen, which the user can tap and hold
to invoke the related context Menu. To display the TextView and ListView in Our application,
modify activity_context_menu_app.xml to appear as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
<ListView
android:id="@+id/listvw"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="false"/>
</LinearLayout>
 To display the related context Menu and information about the selected item, let's add the code
shown below to the ContextMenuAppAct ivity. java.
package com.androidunleashed.contextmenuapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.view.ContextMenu;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ArrayAdapter;
public class ContextMenuAppActivity extends Activity {
private TextView selectedOpt;
String[] fruits={"Apple","Mango","Orange","Grapes","Banana"};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_context_menu_app);
selectedOpt = (TextView) findViewById(R.id.selectedopt);
selectedOpt.setText("Tap and hold a menu item to display its context menu");
ListView myListView = (ListView) findViewById(R.id.listvw);
final ArrayAdapter<String> arrayAdpt = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, fruits);
myListView.setAdapter(arrayAdpt);
registerForContextMenu(myListView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo
menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.listvw) {
AdapterView.AdapterContextMenuInfo info =
(AdapterView.AdapterContextMenuInfo) menuInfo;
if (fruits[info.position] == "Apple") {
menu.setHeaderTitle(fruits[info.position]);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menul, menu);
}
if (fruits[info.position] == "Mango")
{ menu.setHeaderTitle(fruits[info.position]);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2, menu);
}} }
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo
info=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.cut_item:
selectedOpt.setText("You have selected the Cut option of " +
fruits[info.position]+" menu");
break;
case R.id.copy_item:
selectedOpt.setText("You have selected the Copy option of " +
fruits[info.position]+" menu");
break;
case R.id.open_item:
selectedOpt.setText("You have selected the Open option of " +
fruits[info.position]+" menu");
break;
case R.id.close_item:
selectedOpt.setText("You have selected the Close option of the"+
fruits[info.position]+" menu");
break;
}
return true;
} }
 When we run the application, we see output as shown below

P.SEKHAR 30
Using the ActionBar:
 The ActionBar is a widget that replace title bar at top of every Activity displaying navigation and
important functionality of an application. By default, the ActionBar includes the application logo on
the left side, followed by the Activity title, and menu items (if any) on the right side.
 The ActionBar helps in displaying key actions commonly used in an application that we want to be
visible on the screen while running the application. The application's logo acts as a link to the
application's home.
 On Android 3.0 and higher, items from Options Menu are presented by ActionBar. The ActionBar
provides the following features:
1. Customizes the title bar of an Activity.
2. Follows its own life cycle.
3. Consistently displays frequently used actions of an application. The menu items from options
Menu are displayed in the ActionBar. The menu items displayed in the ActionBar are also called
action items. The menu items of the Overflow Menu can be seen by selecting the Menu button on
the device or the Overflow Menu button in the ActionBar.
4. Appears in three forms: standard, tabbed, and list.
5. Makes it possible to use the application's icon or logo for navigation.
6. Through the ActionBar we can even display Action Views, that is, custom views in the
Activity's title bar. For example, we can display the search widget in the ActionBar.
 The ActionBar includes the components are
1. Application's Icon/Logo—Displayed at the upper left on the ActionBar.
2. Activity Title—Displays the title for the ActionBar.
3. Tabs—Displays the tabs of the ActionBar if the navigation mode set is tabs.
4. Drop-Down List—Displays the action items in the form of a drop-down list if the
navigationmode set is list navigation. We learn about navigation mode soon.
5. Actionltems—Displays the menu items of the Options menu in the ActionBar.
6. Action Views—Displays Custom Views in the ActionBar.
7. Overflow Menu—Displays menu items that could not be accommodated in the ActionBar.

Enabling the ActionBar:


 The ActionBar is enabled if an application uses the default Theme .Holo theme and whose
target SDK version is n or higher.
Example: <uses-sdk android:targetSdkVersion="15" />
 To toggle visibility of an ActionBar at runtime, we can use its show and hide methods as follows:
ActionBar actionBar = getActionBar();
actionBar.hide(); // It hides the actionbar
actionBar.show(); // Makes the actionbar visible
 In the preceding code, the getActionBar () method is called to get an ActionBar object, and its hide0
and show() methods are for hiding and showing the ActionBar.
 To hide the ActionBar in an Activity, we can also apply a theme that doesn't support it. In the
AndroidManifest.xml file, set the theme for the Activity to Theme.Holo.NoActionBar as shown in
the following code:
<activity android:label="@string/app_name"
android:name=".ActionBarApp"
android:theme="@android:style/Theme.Holo.NoActionBar" >
 The icon or logo displayed in the ActionBar can be modified through the android: icon attribute in
configuration file AndroidManifest.xml. We can use android: logo attribute for the same purpose.
 The visibility of the icon or logo in the ActionBar is controlled by passing a Boolean value to the
setDisplayShowHomeEnabled () method.
 The following statement hides the logo or icon in the ActionBar:
actionBar.setDisplayShowHomeEnabled(false);
 The following statement makes the logo or icon visible in the ActionBar:
actionBar.setDisplayShowHomeEnabled(true);
 Similarly, the visibility of the title in the ActionBar can be controlled by passing a Boolean value to
the setDisplayShowTitleEnabledO method.
 The following statement hides the title in the ActionBar:
actionBar.setDisplayShowTitleEnabled(false);
 The following statement shows the title in the ActionBar:
actionBar.setDisplayShowTitleEnabled(true);

Using an Application's Icon for Navigation:


 The logo or icon displayed in an ActionBar if clicked navigates you to the home of the application.
By default, the logo or icon displayed in the ActionBar is nonclickable.
 To make the logo or icon clickable, we must call the ActionBar's setHomeButtonEnabied() method,
passing the Boolean value true to it as shown here:
actionBar.setHomeButtonEnabled(true);
 Clicking the logo or icon is considered a Menu Item click. Like Menu Item clicks, the logo or icon
clicks too are handled by onOptionItemSelected() method. It is called passing the Menu Item with
the ID android.R.id.home to it as a parameter as shown here:
@Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case (android.R.id.home) :
Intent intent = new Intent(this, DemoActionBarActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}

Displaying Action Items:


 To display menu items in the ActionBar as action items, we need to add an android: showAsAction
attribute to the menu items while defining them in the menu file. The showAsAction attribute
determines how to display the action item.
 The value of the showAsAction attribute can be any one of the following:
1. always — Makes the action item appear on the ActionBar.
2. if Room — Makes the action item appear in the ActionBar, but only if there is room available
on the ActionBar. If there's not enough room, the item appears in the Overflow Menu.
3. Never — Makes the menu item appear in the Overflow Menu.
 To display the Overflow Menu, press the Menu button on the AVD or a soft options menu button that
appears as three vertical dots on the physical device.
 Let's create a new Android project called DemoActionBar. In this application, we create six Button
controls that are used to show/hide the ActionBar, the application's logo, and Activity's title bar.
 The application displays an action item called create, which when selected navigates us to a new
Activity, createActivity. From new Activity, when we select the application's logo, we are navigated
back to the main Activity. The application also displays an ActionView in form of a search widget.
 After we create the project, the first thing we do is to define Six Button controls in the layout file.
Six Button controls are used to show/ hide the ActionBar, application's logo, and Activity's title bar.
The code written in the layout file activity_demo_action_bar.xml is as shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/show_action"
android:text="Show ActionBar"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hide_action"
android:text="Hide ActionBar"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/show_title"
android:text="Show Title"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hide_title"
android:text="Hide Title"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/show_logo"
android:text="Show Logo"/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/hide_logout"
android:text="Hide Logo"/>
</LinearLayout>

 We see that the Button controls are assigned the IDs show action, hide_action, show_titie, hide_titie,
show_logo, and hide_logo. Also, the caption assigned to the Button controls signifies the task they
are supposed to perform.
 The captions assigned to the Button controls are Show ActionBar, Hide ActionBar, Show Title, Hide
Title, Show Logo, and Hide Logo.
 Next, we need to define an action item, create, in our application. This action item when selected
navigates us to the new Activity in the application. The action item is nothing but the menu item
from the options Menu that is displayed in the ActionBar to be accessed instantly.
 We can define action items in the menu file activity_demo_action_bar.xml that is provided by
default in the res/menu folder of our application.
 In the menu file, we define two menu items, create and search, where create is displayed in
ActionBar as action item, and Search is used to display a search widget in the form of ActionView.
The activity_demo_action_bar.xml file, after defining the two menu items shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="Create"
android:icon="@drawable/create"
android:orderlnCategory="0"
android:showAsAction="ifRoom|withText"/>
<item android:id="@+id/menu_search"
android:title="Search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView"/>
</menu>
 Because we want to represent the action item create via an icon, an image file, create. png, should be
copied to the res/drawable folders of the application.
 On selecting the create action item, we want to navigate to a new Activity. To define views for the
new Activity, we need to add an XML file to the res/layout folder. So, right-click the layout folder in
the Package Explorer window and select the New, Android XML file option.
 When we navigate to the new Activity, we want to display a text message informing that we have
navigated to the new Activity. For displaying a text message, we define a TextView control in the
new Activity's layout file, create.xml as shown below.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is Create Activity"
android:textStyle="bold"/>
</LinearLayout>
 We see that the preceding layout file defines a TextView control with the initial text, "This is create
Activity". The text message is displayed when we navigate to the new Activity.
 After that we need a Java class file to load the views defined in the layout file. So, add a Java class
file called CreateActivity.java to package com.androidunleashed.demoactionbar of our application.
 In the CreateActivity. java file, we need to write code to perform the following tasks:
1. Load the views defined in the create.xml file.
2. Make the application's logo clickable. Remember, we want the user to be taken to the main
Activity of the application on selecting the application's logo.
3. Navigate to the main Activity file, DemoActionBarActivity.class, of the application.
 For performing all these tasks, we write the code as shown below in the file CreateActivity.java.
package com.androidunleashed.demoactionbar;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
public class CreateActivity extends Activity {
@Override
protected void onCreate(Bundle savedlnstanceState){
super.onCreate(savedlnstanceState);
setContentView(R.layout.create);
ActionBar actionBar = getActionBar();
actionBar.setHomeButtonEnabled(true);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (android.R.id.home) :
Intent intent = new Intent(this, DemoActionBarActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
 In the preceding code, we can see that an ActionBar object, actionBar, is accessed by calling the
getActionBar() method and then the Boolean value true is passed to the setHomeButtonEnabled()
method to make the application's logo clickable.
 Clicking application's logo generates a click event on a menu item with the ID android.R.id.home. In
handler method onOptionsItemSelected(), we check whether menu item with ID android.R.id.home
is clicked, that is, whether the application's logo is clicked.
 If application's logo is found to be clicked, we navigate back to the main Activity of the application,
DemoActionBarActivity .class, by clearing all the activities on the top of the stack. For clearing all
the top activities, we use an intent flag,FLAG_ACTIVITY_CLEAR_TOP.
 We know that no Activity is visible to Android application until it is mentioned in the configuration
file AndroidManifest.xml. To make the newly added Activity createActivity. java visible to the
Android project, a statement is written in the AndroidManifest.xml file.
 Also, to replace the default application's logo with a new logo, we need to write code as shown
below in AndroidManifest.xml file. Only statements in bold are added; the rest is the default code.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.androidunleashed.DemoActionBar"
android:versionCode="1"
android:versionName="l.0">
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="15" />
<application
android:icon="@drawable/home"
android:label= "@string/app_name"
android:theme="@style/AppTheme">
<activity
android:name=".DemoActionBarActivity"
android:label="@string/title_activity_demo_action_bar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".CreateActivity" android:label="@string/app_name" />
</application>
</manifest>
 To display our application's logo, we need to copy an image, home.png, to the res/drawable folders of
our application. The statements added to the AndroidManifest.xml file replace the default
application's logo with the image home .png supplied by us.
 code makes the newly added Activity, CreateActivity. class, visible to the rest of the application. To
enable the ActionBar, the minimum SDK version, that is, the value of the android:minsdkversion
attribute, is set to 11 or higher.
 Finally, it's time to write code in DemoActionBarActivity.java. We need to perform the following
tasks through the main Activity file:
1. Access the six Button controls from the layout file activity_demo_action_bar.xml and map them
to the respective Button objects.
2. Make the three Button controls hide the ActionBar, Activity's title, and application's logo. Also
make the hidden components visible through the rest of the three Button controls.
3. When the user selects the Actionview, search widget in the ActionBar, a text box should pop up
prompting for the text to search for.
4. Navigate to new Activity CreateActivity.class when action item create is select from ActionBar.
 To perform all these tasks, the codes as shown below in Activity file DemoActionBarActivity. java.
package com. androidunleashed. demoactionbar;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.ActionBar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.content.Intent;
public class DemoActionBarActivity extends Activity {
Intent intent;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_action_bar);
final ActionBar actionBar = getActionBar();
Button showAction = (Button) this.findViewById(R.id.show_action);
Button hideAction = (Button)this.findViewById(R.id.hide_action);
Button showTitle = (Button) this.findViewById(R.id.show_title);
Button hideTitle = (Button) this.findViewById(R.id.hide_title);
Button showLogo=(Button) this.findViewById(R.id.show_logo);
Button hideLogo = (Button) this.findViewById(R.id.hide_logo);
showAction.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
actionBar.show();
}
});
hideAction.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
actionBar.hide();
}
});
showTitle.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowTitleEnabled(true);
}
});
hideTitle.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowTitleEnabled(false);
}
});
showLogo.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowHomeEnabled(true);
}
});
hideLogo.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v){
actionBar.setDisplayShowHomeEnabled(false);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
intent = new Intent(this, CreateActivity.class);
startActivity(intent);
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
} }
 On running the application, we see output as shown below.

Replacing a Menu with the ActionBar:


 If we make the menu items of the menu created in that application appear in the ActionBar, it not
only makes the menu items appear consistently throughout the application but also relieves the user
from pressing the Menu button.
 To understand how a menu can be replaced by ActionBar, let's create a new Android project called
ActionBarApp. This application displays the simple menu items, checkable menu items, submenu,
and so on everything in the ActionBar.
 In menu, we use icon images for a few menu items. So, let's copy and paste four icon images,
namely, create.png, insert.png, search.png, and update.png, into the res/drawable folders.
 The resolution and size of the icons should be as follows:
 For ldpi — Resolution should be 120dpi and size 18 x 18px
 For mdpi — Resolution should be 160dpi and size 24 x 24px
 For hdpi — Resolution should be 240dpi and size 36 x 36px
 For xhdpi — Resolution should be 320dpi and size 48 x 48px

P.SEKHAR 40
 After copying the images, define the menu items in the menu file activity_action_bar_app.xml as
shown below.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/create_datab"
android:title="CreateDatabase"
android:icon="@drawable/create"
android:orderlnCategory="0"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/insert_rows"
android:title="InsertRows"
android:icon="@drawable/insert"
android:showAsAction="ifRoom"/>
<item android:id="@+id/list_rows"
android:title="ListRows"
android:showAsAction="ifRoom"/>
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/search"
android:showAsAction="ifRoom|withText"/>
<item android:id="@+id/delete_row"
android:title="Delete"
android:showAsAction="never"/ >
<item android:id="@+id/update_row"
android:title="Update"
android:icon="@drawable/update"
android:showAsAction="always" / >
</menu>
 In the preceding code, we see that the showAsAction attribute is applied to different menu items to
determine whether they should appear in the ActionBar or in the Overflow menu.
 To inflate or merge the menu that we defined in the activity_action_bar_app.xml file in our
application, we write the Java code as shown below in our Activity file ActionBarAppActivity.java.
package com. androidunleashed.actionbarapp;
import android.app.Activity ;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
public class ActionBarAppActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action_bar_app);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{ MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_action_bar_app, menu);
return true;
}
}
 To display the menu or menu items in the ActionBar, we need to inflate or merge our menu defined
in the mymenu.xml file in the menu provided as a parameter to the onCreateoptionsMenu() method.
 Initially, there is no menu item defined in the menu parameter. To inflate the menu that we defined
in the activity_action_bar_app.xml file, we get the MenuInflater from the Activity class. An object,
inflater, is Created Of the MenuInflater class, and its inflate method is called to inflate, or merge, our
own menu defined in the activity_action_bar_app.xmi file with menu parameter of this method.
 On running the application, we get outout as shown below .
 To display checkable menu items and submenus, and to apply shortcuts to the menu items in the
same way as we did in the MenuApp application, we write the code as shown below in the
activity_action_bar_app.xml.
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/create_datab"
android:title="CreateDatabase"
android:icon="@drawable/create"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/insert_rows"
android:title="InsertRows"
android:icon="@drawable/insert"
android:showAsAction="ifRoom"/>
<item android:id="@+id/list_rows"
android:title="List Rows"
android:showAsAction="ifRoom"/>
<item android:id="@+id/search_row"
android:title="Search"
android:icon="@drawable/search"
android:showAsAction="ifRoom|withText" >
<menu>
<group android:checkableBehavior="single">
<item android:id="@+id/search_code"
android:title="Search on Code"
android:checked="true"/>
<item android:id="@+id/search_name"
android:title="Search on Name"
android:alphabeticShortcut="n"
android:numericShortcut="6"/>
<item android:id="@+id/search_price"
android:title="Search on Price" />
</group>
</menu>
</item>
<item android:id="@+id/delete_row"
android:title="Delete"
android:showAsAction="never"
android:alphabeticShortcut="d"
android:checkable="true" />
<item android:id="@+id/update_row"
android:title="Update"
android:icon="@drawable/update"
android:showAsAction="always"
android:alphabeticShortcut="u"
android:numericShortcut="4" />
<menu>
 We see that preceding code includes the android:showAsAction attribute to display menu items in
ActionBar if space permits. Also the <menu> element defined inside the search menu item defines
the submenu consisting of three menu items: Search on Code, Search on Name, and Search on Price.
 The Delete menu item appears as a checkable menu item, as the android:checkable attribute is set to
the Boolean value true for this menu item. The android:alphabeticShortcut and the
android:numericShortcut define shortcut keys of the menu items.
 The android:alphabeticshortcut attribute defines the shortcut key for the full keyboard, whereas the
android:numericShortcut attribute defines the shortcut key from the numeric keypad.
 To show a response when a menu item is selected, we need to define a TextView control in the
layout file activity_action_bar_app.xmlas shown below.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/selectedopt" />
</LinearLayout>
 To identify the TextView in Java code, it is assigned the ID selectedopt. To display the response
when a menu item is selected, modify file ActionBarAppActivity .java to appear as shown below
package com. androidunleashed.actionbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
public class ActionBarAppActivity extends Activity {
private TextView selectedOpt;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_action_bar_app);
selectedOpt=(TextView)findViewById(R.id.selectedopt);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{ MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.activity_action_bar_app, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.create_datab:
selectedOpt.setText("You have selected Create Database option");
break;
case R.id.insert_rows:
selectedOpt.setText("You have selected Insert Rows option");
break;
case R.id.list_rows:
selectedOpt.setText("You have selected List Rows option");
break;
case R.id.search_row:
selectedOpt.setText("You have selected Search Row option");
break;
case R.id.delete_row:
selectedOpt.setText("You have selected Delete Row option");
break;
case R.id.update_row:
selectedOpt.setText("You have selected Update Row option");
break;
case R.id.search_code:
selectedOpt.setText("You have selected Search on Code option");
break;
case R.id.search_name:
selectedOpt.setText("You have selected Search on Name option");
break;
case R.id.search_price:
selectedOpt.setText("You have selected Search on Price option");
break;
}
return true;
}
}

 On running the application, we get output as show below.

Creating a Tabbed ActionBar:


 Tabbed and drop-down list ActionBars display menu items in the form of tabs and dropdown lists.
They are popularly used for fragment transitions within an Activity. In tabbed and drop-down
ActionBars, only one type of navigation can be enabled at a time.
 To display navigation tabs in an ActionBar, its setNavigationMode() method is called, passing the
value ActionBar.NAVIGATION_MODE_TABS as a parameter as follows:
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 After we determine the navigation mode, we add the tabs to the ActionBar by calling its addTab()
method: actionBar.addTab(actionBar.newTab().setText("Create").setTabListener(this));
 The preceding code creates a new tab, sets its text to create, attaches a TabListener to it, and finally
adds the newly created tab to the ActionBar.
 Just as the setText () method used in the preceding code sets the text of the tab, we can also call the
setIcon() method to define an image for the tab. Besides this, we can also call the
setcontentDescription() method to supply more detailed information of the tab.
Example:
Tab tab1 = actionBar.newTab();
tabOne.setText("Create")
.setIcon(R.drawable.ic_launcher)
.setContentDescription('Creating the Database")
.setTabListener(this));
actionBar.addTab(tab1);
 The preceding code adds a tab with the text create to the tabbed ActionBar. The icon assigned to the
tab is the default icon ic_launcher, and a detailed description assigned is "creating the Database" to
inform the user about the purpose of the tab.
 We can better understand the concept of the tabbed ActionBar by a running example. So, create a
new Android project called TabbedActionBarApp. In this application, we create two tabs, create and
update. When either tab is selected, a respective log message is displayed.
 In the Java Activity file of the application, TabbedActionBarAppActivity.java, write the code as
shown in below.
package com.androidunleashed.tabbedactionbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.FragmentTransaction;
import android.util.Log;
public class TabbedActionBarAppActivity extends Activity implements
ActionBar.TabListener {
@Override
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
final ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.addTab(actionBar.newTab().setText("Create").setTabListener(this));
actionBar.addTab(actionBar.newTab().setText("Update").setTabListener(this));
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft)
{ Log.d("Tab", String. valueOf (tab. getPosition ()) + "re-
selected");
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft)
{ Log.d("Tab", String.valueOf (tab.getPosition() ) +
"selected");
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft)
{ Log.d("Tab", String.valueOf (tab.getPosition() ) + "
Unselected");
}
}
 In the preceding code, we can see that an ActionBar object, actionBar, is created by calling the
getActionBar() method. To make the ActionBar appear in the form of tabs, its navigation mode is
set to ActionBar .NAVIGATION_MODE_TABS.
 The Activity title is made invisible by passing the Boolean value false to the
setDispiayshowTitieEnabled() method. Thereafter, two tabs with the text create and update are
created and added to the ActionBar.
 The event listener TabListener is associated with both the tabs. When either tab is selected, the
onTabSelected() method is invoked, and the selected tab is passed to it as a parameter. The
onTabSelected() method displays the log message informing the position of the selected tab.
 The position of tab is zero numbered; that is, first tab is considered to have the position 0, second tab
has position 1, and so on. When a tab is selected, onTabunselected() method is also called, and other
tab that is not selected is passed to it as the parameter. The onTabunselected()method displays the
position of the other tab that is not selected.
 On running the application, we get output as shown below.
Creating a Drop-Down List ActionBar:
 In a drop-down list ActionBar, the menu items are displayed in the form of a drop-down list. It is
popularly used for displaying the content within an Activity on basis of selection made by the user.
 To display a drop-down list in an ActionBar, its setNavigationMode() method is called, passing the
value ActionBar.NAVIGATION_MODE_LIST as a parameter to it as shown here:
actionBar. setNavigationMode (ActionBar.NAVIGATI0N_M0DE_LIST) ;
 The drop-down list as expected appears like a spinner, displaying a list of available options,
allowing us to select one of them. For displaying options in the drop-down list, we use the Adapter
that implements the SpinnerAdapter interface, like an ArrayAdapter or simpleCursorAdapter.
 We use an ArrayAdapter in this application. First, we define a string array containing the strings that
we want to be displayed in the drop-down list. Thereafter, we create an ArrayAdapter that displays
the elements of the array in the form of drop-down items.
 Finally, ArrayAdapter is assigned to ActionBar for displaying menu items. To assign ArrayAdapter
to the ActionBar and to attach the event listener to the drop-down items that are displayed,
setListNavigationCallbacks() method is called, passing adapter and onNavigationListener to it as
parameters as shown in the following code:
String[] items = new String[] { "Create", "Insert", "Update", "Search" };
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, items);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, onNavigationltemSelected);
 In the preceding code, the string array items are defined consisting of the strings that we want to
display in the drop-down list ActionBar. An ArrayAdapter called adapter is created comprising the
string array items and casting the array elements in the spinner drop-down items.
 An ActionBar object actionBar is created and its navigation mode is set to
ActionBar,NAVIGATION_MODE_LIST. The setListNavigationCallbacks() method is called on the
actionBar passing the ArrayAdapter, adapter, and listener, onNavigationselected, to it as parameters.
 When a user selects an item from the drop-down list, the onNavigationItemSelected handler is called
where we can write the code to perform the desired action.
 Let's create a new Android project called ListActionBarApp. In this application, we display a few
menu items in form of drop-down list, and when any menu item is selected, respective log message
is displayed. Write the code as shown below in ListActionBarAppActivity. java
package com. androidunleashed.listactionbarapp;
import android.app.Activity;
import android.os.Bundle;
import android.app.ActionBar.OnNavigationListener;
import android.app.ActionBar;
import android.widget .ArrayAdapter;
import android.util.Log;
public class ListActionBarAppActivity extends Activity {
public void onCreate(Bundle savedlnstanceState) {
super.onCreate(savedlnstanceState);
String[] items = new String[] { "Create", "Insert", "Update", "Search" };
ArrayAdapter<String>adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, items);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, onNavigationltemSelected);
}
OnNavigationListener onNavigationltemSelected = new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemld) {
Log.d("Option ", String.valueOf(itemld) + " is selected");
return true;
}
}; }
 In the preceding code, we notice that when an item from the drop-down list is selected, the
onNavigationItemSelected () method is called. The parameters itemPosition and itemId in the
onNavigationItemSelected() method contain information about the position and ID of selected item.
 A log message is displayed in this method displaying ID of selected item. The IDs are sequentially
assigned to the items in the dropdown list beginning with 0. To enable the ActionBar, don't forget to
set the value of android :minSdkVersion attribute to 11 or higher in the AndroidManifest.xml file.
 On running the application, we get output as shown below

P.SEKHAR 50

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy