Mad Unit 5 (A)
Mad Unit 5 (A)
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.
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.
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.
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:
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.
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:
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:
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.
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.
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.
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;
}
}
P.SEKHAR 50