Unit-5 Creating Interactive Menus and Actionbars
Unit-5 Creating Interactive Menus and Actionbars
Unit-5
Creating Interactive Menus and ActionBars
Menus and Their Types:
Menus display options in the form of menu items. Choosing a menu item results in the initiation of the
desired task.
1) Options menu
2) Submenu
3) Context menu
Options Menu:
In an Options Menu, the menu items are displayed in the form of text, checkbox or radio buttons.
Options menu also known as the Activity menu, the menu is displayed when a MENU button is clicked.
1) Icon Menu:
The Icon menu appears when the user presses the MENU button on the device.
The Icon Menu shows the first six menu items of the menu in the form of large , finger friendly buttons
arranged in a grid at the bottom of the screen.
The menu items in the Icon menu can display icons as well as text.
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 more button.
By clicking the more button displays Expanded Menu that shows the scrollable list of the rest of the menu
items.
The Expanded Menu can display menu items in the form of text, check box, or Radio buttons.
An Options Menu is the menu when the MENU button on the device is clicked.
It shows menu items in the form of text, check boxes and radio buttons.
An Options menu is defined through an XML file in the “res/menu” folder of the application.
That is, the menu items of the Options Menu are defined in that XML file.
The <item> tag can be used for adding the items to menu.
activity_menu_app.xml
<menu xmlns:android=“http://schemas.android.com/apk/res/android”>
<item android:id=“@+id/crt_db”
android:title=“Create Database”
android:icon=“@drawbale/one”/>
<item android:id=“@+id/inst_rw”
android:title=“Insert Rows”
android:icon=“@drawbale/two”/>
<item android:id=“@+id/lst_rw”
<item android:id=“@+id/srch_rw”
<item android:id=“@+id/dlt_rw”
<item android:id=“@+id/updt_rw”
</meu>
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/tv”/>
</LinearLayout>
MenuAppActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
@Override
Super.onCreate(savedInstanceState) ;
setContentView(R.layout.activity_menu_app);
TextView selectedopt=(TextView)findViewById(R.id.tv);
@Override
Dept. of C.S.E,C.B.I.T-PDTR Page 3
Unit-5
MenuInflater inflt=getManuInfalter();
inflt.inflate(R.menu.activity_menu_app, menu);
return true;
}}
The onCreateOptionMenu() method of the activity is called when the user clicks the MENU button of the
device.
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.
Adding Submenus:
Usually a submenu represents more detailed options for the selected menu item.
A submenu is created by enclosing <item> nodes within the <menu> , where <item> nodes represent
the submenu options and the <menu> node act as root node for submenu.
EX: activity_menu_app.xml:
<menu xmlns:android=“http://schemas.android.com/apk/res/android”>
<item android:id=“@+id/crt_db”
android:title=“Create Database”
android:icon=“@drawbale/one”/>
<item android:id=“@+id/inst_rw”
android:title=“Insert Rows”
android:icon=“@drawbale/two”/>
<item android:id=“@+id/lst_rw”
<item android:id=“@+id/srch_rw”
<menu>
<group android:CheckableBehaviour=“single”>
<item android:id=“@+id/srch_cd”
<item android:id=“@+id/srch_nm”
</group></menu>
</item>
<item android:id=“@+id/dlt_rw”
<item android:id=“@+id/updt_rw”
</menu>
A context menu appears as a floating window and is displayed when the user taps and holds on a widget ,
holds the middle D-pad button , or press the trackball.
The difference between an options menu and a context menu is that the options menu is invoked when
the MENU button is pressed but context menu appears when we press and hold a view.
An activity has multiple views each view can have its own context menu.
An activity can have only a single options menu but many context menus.
mycontext_menu.xml
<menu xmlns:android=“http://schemas.android.com/apk/res/android”>
<item android:id=“@+id/cut_itm”
android:title=“Cut”/>
<item android:id=“@+id/cpy_itm”
android:title=“Copy”/>
<item android:id=“@+id/unst_itm”
android:title=“uninstall”/>
<item android:id=“@+id/rmv_itm”
android:title=“Remove”/></menu>
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/tv1”/>
<TextView
android:layout_width=“match_parent”
Dept. of C.S.E,C.B.I.T-PDTR Page 6
Unit-5
android:layout_height=“wrap_content”
android:id=“@+id/tv2”/>
</LinearLayout>
Step-3:
a) Link the context menu with the view. By using registerForContextMenu() method we can do that.
@Override
super. onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_app);
TextView selectedopt=(TextView)findViewById(R.id.tv2);
TextView contxtvw=(TextView)findViewById(R.id.tv1);
registerForContextMenu(contxtvw);
@Override
super.onCreateContextMenu(menu , v, menuInfo);
if(v.getId()==R.id.tv2)
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.mycontext_menu , menu);
menu.setHeaderIcon(“R.drawable.one”);
ContextMenuInfo act as adapter for passing any other information about menu inflation.
To apply context menus to ListView control let’s create a new android application called
ContextMenuApp.
mycontext_menu1.xml:
<menu xmlns:android=“http://schemas.android.com/apk/res/android”>
<item android:id=“@+id/cut_itm”
android:title=“Cut”/>
<item android:id=“@+id/cpy_itm”
android:title=“Copy”/></menu>
mycontext_menu2.xml:
<menu xmlns:android=“http://schemas.android.com/apk/res/android”>
<item android:id=“@+id/opn_itm”
android:title=“Open”/>
<item android:id=“@+id/cls_itm”
android:title=“Close”/></menu>
The TextView directs the user to take desired action and tells the user which item from the listview is
selected by user.
The ListView control used to display different items on the screen, which the user tap and hold to invoke
the related ContextMenu.
Dept. of C.S.E,C.B.I.T-PDTR Page 8
Unit-5
activity_context_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/tv”/>
<ListView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/lstvw”/>
</LinearLayout>
ContextMenuAppActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.MenuInflater;
import android.widget.TextView;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.ListView;
Dept. of C.S.E,C.B.I.T-PDTR Page 9
Unit-5
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
@Override
Super.onCreate(savedInstanceState);
setContentView(R.layout.activity_context_menu_app);
ListView mylstvw=(ListView)findViewById(R.id.lstvw);
mylistvw.setAdapter(arrayAdpt);
registerForContextMenu(Mylstvw);
@Override
super.onCreateContextMenu(menu , v, menuInfo);
if(v.getId()==R.id.lstvw);
if(fruits[info.position]==“Apple”)
{
Dept. of C.S.E,C.B.I.T-PDTR Page 10
Unit-5
menu.setHeaderTitle(fruits[info.position]);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.mycontext_menu1,menu)
};
if(fruits[info.position]==“Mango”)
menu.setHeaderTitle(fruits[info.position]);
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.mycontext_menu2,menu);
Using ActionBar:
The ActionBar is a widget that replaces the title bar at the top of every Activity displaying
By default the ActionBar includes the application logo on the left side, followed by Activity title, and
menu items on the right side.
1) Standard ActionBar
2) Tabbed ActionBar
3) List ActionBar
ActionBar ab=getActionBar();
To display action items of ActionBar we need to use the attribute called ShowAsAction. For this attribute
we can able to pass 3 values. Those are:
1) always: If we specify this values it makes the action item to appear on the ActionBar.
2) ifRoom: If we specify this values it makes the action item to appear only when there is Room
(space)available.
3) never: If we specify this values it makes the action item to appear in the Overflow menu.
activity_demo_action_bar.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/tv”/>
</LinearLayout>
DemoActionBarActivity.java
import abdroid.app.ActionBar;
import abdroid.app.Activity;
import abdroid.Content.Intent;
import abdroid.os.Bundle;
import abdroid.view.MenuItem;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_action_bar);
ActionBar ab=getActionBar();
ab.display();
In this type of ActionBars there is only one type of navigation can be enabled at a time.
setNavigationMode(ActionBar.NAVIGATION_MODE_TABS)
After we determine the navigation mode, we add the tabs to the actionbar by calling addTab() method.
activity_demo_action_bar.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/tv”/>
</LinearLayout>
DemoTabbedActionBarActivity.java
import abdroid.app.ActionBar.Tab;
import abdroid.app.Activity;
import abdroid.os.Bundle;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo_action_bar);
ActionBar ab=getActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Dept. of C.S.E,C.B.I.T-PDTR Page 14
Unit-5
ab.addTab(actionBar.newTab().setText(“Create”).setTabListener(this));
ab.addTab(actionBar.newTab().setText(“Update”).setTabListener(this));
ab.addTab(actionBar.newTab().setText(“Delete”).setTabListener(this));
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 the basis of the selection made by
user.
To display a drop-down list in an ActionBar, its setNavigationMode() method is called by passing the
value ActionBar.NAVIGATION_MODE_LIST as a parameter.
The drop-down list appears like a spinner, displaying a list of available options, allowing us to select one
of them.
To assign the ArrayAdapter to the ActionBar and to attach the event listener to the drop-down items that
are displayed, the setListNAvigationCallbacks() method is called.
The below shown code can be used for Creating a Drop-down list ActionBar:
ActionBar ab=getActionBar();
ab.setNavigationMode(ab.NAVIGATION_MODE_LIST);
ab.setListNavigationCallbacks(arrayadpt, onNavigationItemSelected);
In the above code items is defined , consisting of the Strings that we want to display in the drop-down
List ActionBar.
An ArrayAdapter called arrayadpt is created for comprising the string array items to spinner.
An ActionBar object ab is created and its navigation mode is set to ab.NAVIGATION_MODE_LIST for
getting the navigation between items.
setListNavigationCallbacks() method is called on the ActionBar for passing the ArrayAdapter and
eventListener .
Using Databases:
User entered Data needs to be saved somewhere so that it can be accessed at a later time.
Android offers the SQLite relational database library for data management.
SQLite is an open source , lightweight, and powerful database available in the form of a C library.
It uses SQL(structured Query Language) for storing and retrieving information and performing database
maintenance.
To create an Android application that stores, accesses, and manipulates user information we need to use
SQLiteOpenHelper class.
This is an abstract class that used to create ,open , and update database.
SQLiteDatabase class also provides methods including insert(), and query() which are used for inserting
rows in table and to execute different SQLite queries .
activity_database_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/response”/>
<TextView
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/prodrec”/>
<TableLayout
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/add_tab”>
<TableRow>
<TextView
<EditText
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/prod_code”/>
</TableRow>
<TableRow>
<TextView
<EditText
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/prod_name”/>
Dept. of C.S.E,C.B.I.T-PDTR Page 17
Unit-5
</TableRow>
<TableRow>
<TextView
<EditText
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/prod_price”/>
</TableRow>
<TableRow>
<Button
android:text=“Add Product”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/add_button”/>
<Button
android:text=“Cancel”
android:layout_width=“match_parent”
android:layout_height=“wrap_content”
android:id=“@+id/canel_button”/>
</TableRow></TableLayout></LinearLayout>
DatabaseManager.java
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.database.sqlite.SQLiteOpenHelper;
Dept. of C.S.E,C.B.I.T-PDTR Page 18
Unit-5
import android.content.Content;
import androi.content.ContentValues.
import android.util.log;
private static final string CREATE_TABLE= “CREATE TABLE”+DB_TABLE+(code INTEGER PRIMARY KEY,
product_name TEXT, price FLOAT);”;
public DatabaseManager(Context c)
this.context=c;
helper=new SQLHelper(c);
this.db= helper.getWritableDatabase();
helper=new SQLHelper(context);
db=helper.getReadableDatabase();
return this;
helper.close();
newprod.put(“code”,c);
newprod.put(“product_name”,n);
newprod.put(“price”,p);
try
catch(Exception e)
return false;
db.close();
return true;
}
Dept. of C.S.E,C.B.I.T-PDTR Page 20
Unit-5
super(c,DB_NAME,DB_VERSION);
@Override
db.execSQL(CREATE_TABLE);
All three communication mediums- SMS , email and voice calls –use the concept of Broadcast Receivers.
BroadCast receiver is a component that responds to different messages that are broadcast by the system
or other applications.
Messages like download complete, battery low, image captured, require attention.
Such messages are broadcast as an Intent , intent is an object that is waiting for broadcast receivers to
respond and such broadcasted intents and take the necessary actions.
1) Broadcasting an Intent
Broadcasting an Intent:
To broadcast an Intent, we first create an Intent object and assign a specific action to it.
broadint.setAction(BROADCAST_STRING);
sendBroadcast(broadint);
String actionName=inte.getAction();
String msg=inte.getStringExtra(“message”);
}}
The android notification system provides us with several ways of alerting users.
Notifications are usually displayed on the status bar at the top of the screen.
The simplest type of notification is status, which appears in the status bar as an icon along with some
optional ticker text.
Users can pull down the status bar to see the notification list and clear the notification by clicking the
Clear button.
After tapping the notification, the user navigates to the Intent defined by the notification.
1) Notification:
The object that defines the information to be displayed, which can be text to be displayed on thestatus/expended
status bar and an icon , and the no of times the notification triggered and so on.
2) NotificationManager:
The base object with which notifications are handled. It displays the information encapsulated in the Notification
object, which is displayed via the notify() method.
notif.icon=R.drawable.one;
notif.when=System.CurrentTimeMillis();
notif.flags |=Notification.FLAG_AUTO_CANCEL;
flag: Assigns the constant that determines the subsequent action when the notification is selected from
the notification window.
We can also assign a notification icon , ticker text, and time of occurrence through the Notification object
constructor, as shown below:
To implement the SMS Messaging facility in our application, Android provides a built-in class known as
SmsManager , which we use to send and receive SMS messages.
To send and receive SMS messages in an application we need to use permissions first. All the permissions
were define under AndroidManifest.xml
We need to write the below lines for sending and receiving SMS.
For sending:
<uses-permission android:name=“android.permission.SEND_SMS”/>
For Receiving:
<uses-permission android.name=“android.permission.RECEIVE_SMS”/>
For receving sms along with the above permissions we need to write the below code in Manifest.xml
<receiver android:name=“.ReceiverSMS”>
<intent-filter>
<action android:name=“android.provider.Telephony.SMS_RECEIVED”/>
</intent-filter>
</receiver>
To send an sms messgae with java code we use the SmsManager class. And then we can access the
sendTextMessage() method of that class as shown below:
SmsManager sms=SmsManager.getDefault();
2) Service_centadd: represent the Service center address. we use value null for default
We also can create and register two BraodcastReceivers, which listen for Intents that match sent and
delivered as shown by the following code:
For Receiving sms we need to write the following code in java program:
First we need to give permission from the manifest file by using the below code:
<uses-permission android:name=“android.permission.RECEIVE_SMS”/>
To listen incoming messages we need to register our Broadcast Receiver class using an Intent filter by
using the following code in manifest file :
<receiver android:name=“.ReceiverSMS”>
<intent-filter>
<action android:name=“android.provider.Telephony.SMS_RECEIVED”/>
</intent-filter> </receiver>
In java program we can use the below methods for code for Receiving the sms:
Bundle bund=inte.getExtras();
SmsMessage[ ] msg=null;
if(bund!=null)
msg=new SmsMessage[pdus.length];
msg[i]=SmsMessage.createFromPdu((byte[ ])pdus[i]);
Str+=msg[i].getMessageBody().toString();
}}
The information exists in the bundle in the form of an array of SMS PDUs.
PDU stands for Protocol Data Unit and is used to encapsulate the SMS message.
The array of SMS PDUs is thereafter converted into an array of SmsMessage objects.
To convert each PDU byte array into an SMS Message object, the SmsMessage.createFromPdu() method
is called.
Sending e-mail:
Intent.ACTION_SEND
First we need to configure the email account. For that follow the below steps:
Once the e-mail account configured then by using ACTION_SEND we can send messages.
Then we need to set the type of data what we are sending for that:
emailIntent.setType(“plain/text”)
Then we call startActivity() with the CreateChooser() method. This one allows the user to handle the
Intent by selecting the application as shown below:
To supply data for the email message fields, we set certain standard extras for the Intent. like:
After setting up the all Intent’s extras, launch the activity to initiate the sending email task.
The android telephony APIs include the Telephony Manager that access the telephony services on the
device and enables us to
1) Provide a user interface for entering or modifying the phone number to dial.
The simplest way to make an outgoing call is to invoke the Dialer application by using the
Intent.ACTION_CALL action.
callIntent.setData(uri.parse(“tel:1111122222”));
startActivity(callIntent);
The above code initiates a phone call to 1111122222 using the system in-call Activity.
For making phone call we need to give permission to invoke the Dailer application. For that in Manifest
file we need to write the below code:
<uses-permission android:name=“android.permission.CALL_PHONE”/>
android.intent.action.PHONE-STATE
To access phone state information we need to get permissions for that we need to write the below code
in manifest file:
<uses-permission android:name=“android.permission.READ_PHONE_STATE”/>