Module - 4: Working With Menus
Module - 4: Working With Menus
BCA/BCS – SEMESTER 6
S.A
Working with Menus
➢Android SDK has extensive support for menus. Menu provides a familiar
and consistent User Interface.
➢It supports regular menus, submenus, context menus, icon menus,
secondary menus and alternative menus
➢Menu is an important User Interface component in Android.
➢Now Android 4.0 has introduced pop-up menus: menus that can be
invoked at any time based on a button click.
➢In Android, menus, much like other resources, can be represented as both
Java object and in XML files.
➢Android generates resource IDs for each of the loaded menu items.
1. Understanding Android Menus
➢Some of these menu item sort-order number ranges are reserved for
certain kinds of menus. These are called menu categories.
➢The available menu categories are as follows Secondary menu items,
System menu items, alternative menu item, Container menu items.
➢Two callback methods are used to create and respond to menu items:
onCreateOptionsMenu() [to create an options menu] and
onOptionsItemSelected() [to respond to menu items].
2. Creating a Menu
➢Activity is associated with a single menu, Android creates this single menu for
that activity and passes it to the onCreateOptionsMenu() callback method of the
activity class.
➢Menus in Android are also known as options menus.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// populate menu items
.....
...return true;
}
➢Once the menu items are populated, the code should return true to make the
menu visible. If this method returns false, the menu is invisible.
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
//call the base class to include system menus
super.onCreateOptionsMenu(menu);
menu.add(0,1,0,"append");
menu.add(0,2,1,"item2");
menu.add(0,3,2,"clear");
return true;
}
➢The first parameter required for adding a menu item is the group ID (an integer)[to
which group the menu belongs].
➢The second parameter is the menu item ID, which is sent back to the callback function
when that menu item is chosen.
➢The third argument represents the order ID.
➢The last argument is the name or title of the menu item.
Menu.xml file
➢There is one more convenient and preferable way of creating a menu - using an
xml-file.
➢To get a menu which we have created programmatically, we will
create mymenu.xml file in res/menu folder:
<menu >
<item android:id="@+id/item1"
android:title=“@string/str1"/>
<item android:id="@+id/item2"
android:title="@string/str2"/>
<item android:id="@+id/item3"
android:title="@string/str3"/>
</menu>
➢Menu hierarchy is created using the menu tag as the root node and a series of item tags to
specify each menu item.
➢Each menu item node supports a set of attributes
➢To use the resources, implement the MenuInflater class within your
onCreateOptionsMenu() or onCreateContextMenu() event handler.
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater mi= getMenuInflater().;
mi.inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1: t1.setText(“The Selected Item is : 1”);
return true;
case R.id.item2: t1.setText(“The Selected Item is : 2”);
return true;
case R.id.item3: t1.setText(“The Selected Item is : 3”);
return true;
default: return super.onOptionsItemSelected(item);
} }
3. Working with Menu Groups
➢Now, let’s look at how to work with menu groups. shows how you add
two groups of menus: Group 1 and Group 2.
public boolean onCreateOptionsMenu(Menu menu)
{
//Group 1
int group1 = 1;
menu.add(group1,1,1,"g1.item1");
menu.add(group1,2,2,"g1.item2");
//Group 2
int group2 = 2;
menu.add(group2,3,3,"g2.item1");
menu.add(group2,4,4,"g2.item2");
return true; // it is important to return true
}
➢A group’s menu items can be manipulated using these methods: removeGroup(id),
setGroupCheckable(id, checkable, exclusive), setGroupEnabled(id,boolean enabled),
setGroupVisible(id,visible)
removeGroup(id)
removeGroup() removes all menu items from that group, given the group ID.
setGroupEnabled(id,boolean enabled)
Menu items can be enabled or disabled in a given group using the setGroupEnabled
method().
setGroupVisible(id,visible)
You can control the visibility of a group of menu items using setGroupVisible().
<item
android:id="@+id/BackGreen"
android:title="Green" />
<item
android:id="@+id/BackBlue"
android:title="Blue" />
</menu>
</item>
</menu>
Context Menus
➢A context menu can be accessed by right-clicking a UI element.
➢In Android context menus is accessed by a long click on view.
➢A long click is a mouse click held down slightly longer than usual on.
➢A context menu is represented by ContextMenu class in the Android
menu architecture.
➢Just like a Menu, a ContextMenu can contain a number of menu
items.
➢An activity owns a regular options menu, whereas a view owns a
context menu.
➢So an activity can have only one options menu but many context
menus.
➢Because an activity can contain multiple views, and each view can
have its own context menu, an activity can have as many context menus
as there are views.
Activities, views, and context menus
➢onCreateContextMenu() : - To create a context menu. A context menu is owned by a view.
➢onContextItemSelected() :- Call back method invoked when context menu item is selected.
➢The steps to implement a context menu :
1. Register a view for a context menu in an activity’s onCreate() method.
2. Populate the context menu using onCreateContextMenu().
3. Respond to context menu clicks.
registerForContextMenu(tv);
}
b). Populating a Context Menu
➢Android calls the onCreateContextMenu() method with a view for populating the
menu.
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo)
{
// statements ;
}
➢The onCreateContextMenu() callback method provides three arguments to work with
1. ContextMenu menu :- a ContextMenu object.
2. View v :- the view (such as the TextView)
3. ContextMenuInfo menuInfo :- the ContextMenuInfo class
➢Example
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo)
{
menu.setHeaderTitle("Sample Context Menu");
menu.add(0,1,1,"item1");
}
c). Responding to Context Menu Items
➢The third step in the implementation of a context menu is responding to context
menu clicks.
➢Android provides a callback method similar to called onContextItemSelected()
for responding to context menu click.
public boolean onContextItemSelected(MenuItem item)
{
if (item.getitemId() = some-menu-item-id)
{
//handle this menu item
return true;
}
}
Dynamic Menus
➢To create dynamic menus, use the onPrepareOptionsMenu() method
that Android provided on an activity class.
➢This method resembles onCreateOptionsMenu() except that it is
called every time a menu is invoked.
➢It is called when the user wants to make a choice. Here Menu items
can be dynamically added when the activity is invoked.
Loading Menus Through XML Files
➢All menu files start with the same high-level menu tag followed by a series of
group tags.
➢Each of these group tags corresponds to the menu item group.
➢You can specify an ID for the group using the @+id approach.
➢Each menu group has a series of menu items.
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
<item
android:id="@+id/three"
android:title="Three"/>
</menu>
Working with a Pop-up Menu :
private void showPopupMenu()
{
TextView tv = getTextView();
PopupMenu popup = new PopupMenu(this, tv);
popup.inflate(R.menu.popup_menu);
popup.setOnMenuItemClickListener(new
PopupMenu.OnMenuItemClickListener()
{
public boolean onMenuItemClick(MenuItem item)
{
appendMenuItemText(item);
return true;
}});
popup.show();
}
❖A pop-up menu is used on demand, whereas an options menu is
always available.
❖A pop-up menu is anchored to a view, whereas an options menu
belong to the entire activity.
❖A pop-up menu uses its own menu item callback, whereas the
options menu uses the onOptionsItemSelected() callback on the
activity.
Working with Toast
➢A Toast is like an alert dialog that has a message and displays for a certain
amount of time and then disappears after timeout.
➢It does not have any buttons.
➢Toast is also known as transient alert message. show() method is used to display
toast.
➢It provides a simple message about an operation performed.
Synatx :
Parameters :
Context : Name of the activity which invoke the Toast.
Text : Message for display.
Duration : how long the toast will show. It contains 2 value
Toast.LENGTH_LONG
Toast.LENGTH_SHORT
Example :
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.but1);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
s1="Welcome to Android";
Toast.makeText(MainActivity.this,
s1,Toast.LENGTH_LONG).show();
}
});}
BCA/BCS – SEMESTER 6
S.A
1). What Is a Fragment?
➢A fragment is a reusable class implementing a portion of an activity.
➢A Fragment typically defines a part of a user interface and it has its own layout
and life cycle. It’s flexible and reusable. A Fragment can be used in multiple
activities.
➢Fragments must be embedded in activities; they cannot run independently of
activities. A fragment is an independent Android component which can be used by
an activity.
➢It is also possible to define fragments without an user interface, i.e., headless
fragments.
➢Android devices exists in a variety of screen sizes and densities.
➢Fragments also support different layout for landscape and portrait orientation on
a smartphone.
➢It is possible to dynamically add and remove fragments from an
activity. The usage of fragments allows to design very flexible user
interfaces. Multiple fragments can be used in an activity to create multi-
pane UI.
➢Fragments implement modularity. Its modular and reusable.
Fragments In Android
➢Here are the important things to understand about fragments:
❖A Fragment is a combination of an XML layout file and a java class much
like an Activity.
❖Using the support library, fragments are supported back to all relevant
Android versions.
❖Fragments encapsulate views and logic so that it is easier to reuse within
activities.
onStart() The onStart() method is called once the fragment gets visible.
onResume() Fragment becomes active.
onPause() Fragment is visible but becomes not active anymore, e.g., if
another activity is animating on top of the activity which contains
the fragment.
onStop() Fragment becomes not visible.
onDestroyView() Destroys the view of the fragment. If the fragment is recreated
from the backstack this method is called and afterwards the
onCreateView method.
onDestroy() Final clean up of the applications state.
onDetach() Detached from Activity.
3).FragmentTransactions and the Fragment
Back Stack
➢Actions such as add, remove, replace etc. can be performed on fragments in
response to user interaction.
➢Scene defines the given state of applications UI. Animated change between two
scenes is called transition. Each set of changes committed to the activity is called
a transaction and transactions are performed using APIs in FragmentTransaction.
➢Each transaction can be saved to a back stack managed by the activity, allowing
the user to navigate backward through the fragment changes (similar to navigating
backward through activities).
➢An instance of FragmentTransaction is acquired from the FragmentManager
FragmentManager fm= getFragmentManager();
FragmentTransaction ft = fm. beginTransaction();
➢To apply the transaction to the activity, you must call commit().
➢Before calling commit(), call addToBackStack(), in order to add the transaction
to a back stack of fragment transactions.
➢The back stack is managed by the activity and it allows the user to return to the
previous fragment state, by pressing the Back button.
➢Fragment Transaction Methods.
Task
➢Task is a collection of activities that user perform while doing a job.
➢An activity is launched in a new task from the home screen.
➢By default all the activities in an application belong to the same task.
➢Activities in a task can exist in the foreground, background as well as on back stack.
➢By calling addToBackStack(), the transaction is saved to the back stack so the
user can reverse the transaction and bring back the previous fragment by pressing
the Back button.
➢To retrieve fragments from the back stack, you must
override onBackPressed() in the main activity class:
BCA/BCS SEMESTER 6
S.A
Action Bar
➢The action bar is an Android UI pattern [design element] that is used to
provide a consistent user interface for key features such as tabs, application
identity, menus, and search. It is also known as app bar.
➢The ActionBar APIs introduce UI themes to provide a consistent look and
feel that allow for tabbed user interfaces.
➢The action bar is a dedicated piece of space at the top of each screen that is
generally persistent throughout the app.
➢The action bar tries to display all of its tabs concurrently and make all the
tabs equal in size based on the width of the widest tab label.
➢It has the powerful capabilities like adapting to screen configurations
(landscape & portrait).
General Organization
➢In Android 3.0 (API level 11), Google introduced the ActionBar APIs to the
Android platform.
➢Action bar mainly contains four functional areas. They are app icon,
view control, action buttons and action overflow.
1. App Icon – App branding logo or icon will be displayed here.
2. View Control – A dedicated space to display app title. It also
provides option to switch between views by adding spinner or
tabbed navigation.
3. Action Buttons – Some important actions of the app can be
added here.
4. Action Overflow – All unimportant action will be shown as a
menu in this part.
Layout Considerations for Split Action Bars
➢Action buttons on the action bar surface refers app's most important
activities. It shows the actions used most often
➢Depending on available screen space, the system shows the most
important actions as action buttons and moves the rest to the action
overflow.
Action overflow
➢ The action overflow in the action bar provides access to app's less
frequently used actions.
➢Action bar tabs offer users a familiar interface for navigating between and
identifying sibling screens in your app. Tabs enable navigation.
➢To create tabs using ActionBar :
1) In the OnCreate method of an Activity – NavigationMode on
the ActionBar must be set toto ActionBar.NavigationModeTabs
2) Create a new tab using ActionBar.NewTab().
3) Assign event handlers or provide a custom ActionBar.TabListener
implementation that will respond to the events that are raised by
user.
4) Add the tab that was created in the previous step to the ActionBar.
1) .Action Bar Navigation Modes :
➢In Tab navigation, navigation mode must be set by passing
NAVIGATION_MODE_TABS as the parameter.
➢There three different navigation type supported:
❖ ActionBar.NAVIGATION_MODE_LIST
❖ ActionBar.NAVIGATION_MODE_STANDARD
❖ ActionBar.NAVIGATION_MODE_TAB
ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
SetContentView(Resource.Layout.Main);
Obtaining an Action Bar Instance :
➢action bar of an activity is accessed by calling getActionbar() on the
activity.
➢Here is that line of code:
ActionBar bar = this.getActionBar();
2). Setting up the Tabs :
➢We’ve got three tabs that are displayed in the action bar.
➢Here’s the code for setting up the tabs:
➢Get an instance of our Action Bar, set the navigation mode to Tabs,
disable displaying the activity’s title and then create the Tab objects
3). Assign event handlers or Listener:
➢Activity should implements the listener so that when user selects
a tab it shows the relative fragment.
➢Each tab in the action bar should be associated with a fragment.
➢When the user selects a tab, the application will display the fragment
that is associated with the tab.
➢ActionBar.TabListener interface provides three callback methods that
Android will invoke when the state of the tab changes:
➢OnTabSelected - This method is called when the user selects the
tab. It should display the fragment.
➢OnTabReselected - This method is called when the tab is already
selected but is selected again by the user. This callback is typically
used to refresh/update the displayed fragment.
➢OnTabUnselected - This method is called when the user selects
another tab. This callback is used to save the state in the displayed
fragment before it disappears.
Example :-
ActionBar ab = getSupportActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(t_one);
actionBar.addTab(t_two);
}
4). Add tab to the Action Bar:
➢Add the tab that was created in the previous step to the ActionBar
using :
ActionBar.addTab(tab1)
➢Example :-
actionBar.addTab(t_one);
actionBar.addTab(t_two);
actionBar.addTab(t_three);
2. Action Bar and Menu Interaction
➢To add actions to the action bar, create a XML file in
the res/menu directory where actions are defined.
➢It is possible to define the actions in Java code, but you will write less
code if you use XML.
<menu >
<item
android:id="@+id/action_search"
android:icon="@drawable/ic_action_search"
android:title="@string/action_search"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_record"
android:icon="@drawable/ic_action_video"
android:title="@string/action_record"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_save"
android:icon="@drawable/ic_action_save"
android:title="@string/action_save"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_label"
android:icon="@drawable/ic_action_new_label"
android:title="@string/action_label"
android:showAsAction="ifRoom" />
<item
android:id="@+id/action_settings"
android:title="@string/action_settings"
android:showAsAction="never" />
</menu>
1). Menu Items as Actions :
➢ Some of the menu items are assigned to appear directly on the action
bar. These menu items are indicated with the tag showAsAction.
➢Here the important xml attributes should be known are
❖ android:icon – Defines the icon of the action item.
❖ android:title – Title for the icon.
❖ android:showAsAction – Defines the visibility of the action item.
It accepts following values.
ifRoom Displays the icon if there is space available on the screen
never Never places this icon on the action bar
Forces to display the icon always irrespective of space available.
always
This way is not suggested.
Displays a text along with the icon. Normally the text value
withText
defined by android:title will be displayed
Defines the action layout associated with it. This action view
collapseActionView
defined using android:actionLayout orandroid:actionViewClass
3. List Navigation Action Bar Activity
➢You need the following additional files to implement list action bar
navigation activity :
❖ SimpleSpinnerArrayAdapter.java: This class provides the rows
required by a drop-down navigation list.
❖ ListListener.java: Acts as a listener to the list navigation activity.
❖ ListNavigationActionBarActivity.java: Implements the list
navigation action bar activity.
1). Creating a Spinner Adapter :
➢Example :-
public class ListListener extends BaseListener implements
ActionBar.OnNavigationListener
{
public ListListener(Context ctx, IReportBack target)
{
}
}}
3). Setting Up a List Action Bar :
➢This class is very similar to the tabbed activity.
➢Example :-
BSC/BCA – SEMESTER 6
S.A
Working with Dialogs
➢A dialog is a smaller window that pops up in front of the current
window to show an urgent message, to prompt the user for a piece of
input, or to show some sort of status like the progress of a download.
➢ The user is generally expected to interact with the dialog and then
return to the window underneath to continue with the application.
➢Dialogs that are explicitly supported in Android include the
❖ alert, prompt
❖ pick-list
❖ single-choice
❖ multiple-choice
❖ Progress
❖ Time-picker and date-picker dialogs. – to select date or time
➢ Android also supports custom dialogs for other needs.
Using Dialogs in Android
➢Dialogs in Android are asynchronous, which provides flexibility.
➢In android dialogs, application has the ability to dismiss the dialog from code,
which is powerful.
➢Android AlertDialog class can be used to display the dialog message with OK
and Cancel buttons. It can be used to interrupt and ask the user about his/her choice
to continue or discontinue.
➢Android AlertDialog is composed of three regions: title, content area and
action buttons. The DialogFragment manages and handles dialog correctly.
➢ Title – Title is optional. Title area displays the title of the message.
➢ Content area – This area displays the message, list, checkbox etc. that is displayed
to the user.
➢ Neutral: Neutral button is used when the user want to neither proceed nor cancel
the action. For example. the action might be "Remind me later.“
}
}
}
b). Displaying a Dialog Fragment
➢Once a dialog fragment is constructed, a fragment transaction is needed to show it.
➢Operations on dialog fragments are conducted through fragment transactions.
➢The show() method on a dialog fragment takes a fragment transaction as an input.
➢To show the dialog box, create an instance of the DialogFragment and call show() method
by passing the FragmentManager and a tag name for the dialog fragment.