Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Android Menu: How to create a Menu in Android

In this article we will see the step by step how to create a menu to your small or big Android Application.

The Android platform allows you to create a rich UI consisting of several useful components, such as menus and tabs. It also allows you to enhance the appearance of your apps by using styles and themes, thereby, providing an enriching user experience. To enhance the UI of your app, you can also create extended or customized views. These views provide you further flexibility for creating an app, without restricting yourselves to the limited capabilities of built-in views. This article explains how to use menus. Further, it discusses how to customize views in order to fulfill specific requirements of an app.

Objectives:

  • Create menus
  • Create tabs
  • Apply styles and themes
  • Customize views

Creating Menus

While developing apps, you need to ensure that the UI created is attractive, occupies less space, and is easy to use. Menus are an important part of the UI. A menu consists of a set of commands. These commands are accessible on the device through a button, key, or gesture. Using menus, you can implement easier navigation within an app and between the apps.

User Special Note: Gestures are used by smartphone users to interact with touch screen devices intuitively, such as a swipe movement with a finger. Android provides an API in the form of the Android Gesture Package, which allows you to store, load, draw, and recognize such gestures.

Consider an example of the Gallery app. The Gallery app enables you to view images stored in various formats. Apart from viewing an image, the Gallery app enables you to perform various actions on images, such as sorting, sharing, printing, and deleting. All these actions further consist of multiple options. For example, if you want to share an image, you have the option to share it via multimedia messaging or Bluetooth. If you try to include all the actions on a single screen, it would make the UI complicated, making it difficult for the user to navigate

Through the options. The best way to implement such an app is by using menus. Android provides you with the following three types of menus:

  • Options menu: This is the primary collection of menu items for an activity, which appears when the user presses the MENU button on the emulator/device, as shown in the following figure.

An
Options Menu

Figure 1: An Options Menu

  • Context menu: This is a floating list of menu items that appears when the user touches and holds a view that is registered to provide a context menu. The following figure shows a context menu that appears when a user long presses the entry for a contact in Contact Manager.

A Context
Menu

Figure 2: A Context Menu

  • Popup menu: This type of menu displays a list of items in a vertical list that is attached to a view. It provides extended actions that relate to regions of content in an activity. The following figure shows a popup menu.

A Popup
Menu

Figure 3: A Popup Menu

Creating an Options Menu

The options menu includes basic actions and necessary navigation items for an activity, such as a button to open the Search app. The options menu items are accessible by using the MENU button.

Creating a Menu Resource

You can define a menu and its items in an XML menu resource, and then inflate the menu resource through code. You can create a menu resource in a separate XML file in your project’s res/menu folder. To create a menu resource, the following elements are used:

  • <menu>: The <menu>element is the root node for the menu resource and acts as a container for the menu items defined by using multiple <item>and <group>elements.
  • <item>: The <item>element is used to create a menu item. The <item>element can consist of nested <menu>elements that are used to create submenus.
  • <group>: The <group>element is an optional element that allows you to categorize the menu items, thereby, allowing sharing of properties, such as visibility and active state.

The following markup shows how to create an options menu in an XML file residing in the res/menu folder:

<menu xmlns:android=“http:// schemas.android.com/apk/res/android” >
  <item android:id=“@+id/Edit” android:title=“@string/edit”/>
  <item android:id=“@+id/SAVE” android:title=“@string/save”/> <item android:id=“@+id/MENU_DELETE” android:title=“@string/delete”/> <item android:id=“@+id/OPEN” android:title=“@string/open”/> <item android:id=“@+id/Add” android:title=“@string/add”/> <item android:id=“@+id/Refresh” android:title=“@string/refresh”/> </menu>

Inflating a Menu

After creating an XML file for the menu, you need to inflate the menu in your main activity. Inflating a menu means instantiating the menu XML files into objects of the Menu interface. Once this is done, the menu can be made visible on the screen. To inflate the options menu, you need to override the onCreateOptionsMenu () method of the activity class. This method is called when the user clicks the MENU button. Inside this method, you need to create an object of the android.view.MenuInflator class. This class provides the inflate(int menuRes, Menu menu) method that is used to inflate the menu declared in the XML resource. The first parameter of this method is the resource ID for the menu’s XML layout. The second parameter refers to the menu to inflate. The following code snippet shows how to inflate an options menu in the activity:

@Override public boolean onCreateOptionsMenu (Menu menu) { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate(R.menu.main, menu); 
  return true; 
  }

Adding Functionality to the Menu Items

Once a menu resource has been created and inflated, you need to add functionality to the menu items to perform some tasks when clicked. To perform a task when a menu item is clicked, you need to override the onOptionsItemSelected()method of the activity, which is called when a menu item is clicked. The following code snippet shows how to implement the onOptionsItemSelected()method:

public boolean onOptionsItemSelected (MenuItem item) {
  // TODO Auto-generated method stub.
  switch (item.getItemId()) 
  { 
  case R.id.Edit: 
  Toast.makeText(getApplicationContext (), “You Clicked On Edit Menu Item”, Toast.LENGTH_LONG).show(); 
  break; 
  case R.id.SAVE: 
  Toast.makeText(getApplicationContext (), “You Clicked On Save Menu Item”, Toast.LENGTH_LONG).show(); 
  break; 
  case R.id.MENU_DELETE: 
  Toast.makeText(getApplicationContext (), “You Clicked On Delete Menu Item”, Toast.LENGTH_LONG).show(); 
  break; 
  case R.id.OPEN: 
  Toast.makeText(getApplicationContext (), “You Clicked On Open Menu Item”, Toast.LENGTH_LONG).show(); 
  break; 
  case R.id.Add: 
  Toast.makeText(getApplicationContext (), “You Clicked On Add Menu Item”, Toast.LENGTH_LONG).show(); 
  break; 
  case R.id.Refresh: 
  Toast.makeText(getApplicationContext (), “You Clicked On Refresh Menu Item”, Toast.LENGTH_LONG).show(); 
  break; 
  }
   return super.onOptionsItemSelected (item);
  }
  }

The following figure shows an options menu that is displayed when a user presses the MENU button.

The
Options Menu

Figure 4: The Options Menu

When an activity is created and the MENU button is clicked, the onCreateOptionsMenu()method is called only once. This means that the system inflates the menu only once, and keeps on using the inflated menu until the activity is destroyed. You can change the options menu after it has been created in the onCreateOptionsMenu()method by using the onPrepareOptionsMenu()method. This method dynamically adds, removes, or enables/disables menu items depending on the current state of an app.

User Special Note: In Android 2.3 and lower, the onPrepareOptionsMenu () method gets executed each time the user opens the options menu. Whereas, in Android 3.0 and higher, it is a must to execute the invalidateOptionsMenu() method to update the menu because the menu is always open. The system will then call the onPrepareOptionsMenu() method to update the menu items.

Creating a Context Menu

A context menu is similar to the menu that gets displayed when the user performs a right-click on a PC. A context menu is used to provide access to actions that are specific to an item. In Android, a context menu gets displayed when the user performs a long press on an item, which is registered to provide a context menu. Context menus can be created for any view, though they are mostly used for items within a list view. When any item in a list view is long pressed and the list is registered to provide a context menu, the selected list item animates its background color in order to signal the user about the context menu getting activated.

User Special Note: You can also create contextual actions by using the contextual action mode. This mode is created by using the system implementation of ActionMode, which is a class that displays a contextual action bar with action items at the top of the UI. If an app allows, it enables the user to perform an action on multiple items at once in the app.

To register a view to provide a context menu, you need to call the registerForContextMenu()method and pass to it the view for which the context menu is required. To define the appearance and behavior of the context menu, you need to override the following callback methods of an activity:

  • onCreateContextMenu(): This method is called when a context menu is about to be shown.
  • onContextItemSelected(): This method is called when an item in the context menu is selected. The onCreateContextMenu()method takes three parameters of the following types:
  • ContextMenu: Refers to the context menu object that is displayed for the activity when a long press is done on a view.
  • View: Refers to the view on which a long press was done to display a context menu. q ContextMenuInfo: Refers to the extra information about the menu item depending on the view for which the context menu is built. Within the onCreateContextMenu()method, you need to add items to the context menu. You can add items to the context menu by using the Menu.add() method. This method takes four parameters, which are described in the following table.

The Parameters of the Menu.add() Method

Parameter

Description

int groupId

The group ID of the group to which the menu item should belong. If you do not want a menu item to belong to any group, use the value, Menu. NONE, for this parameter.

int itemId

A unique ID for the menu item. If you do not want a menu item to have a unique ID, use the value, Menu. NONE, for this parameter.

int order

The order of the menu item in the list. If you do not want any specific order for the menu items, use the value, Menu. NONE, for this parameter.

CharSequence title

The text to be displayed on the menu item.

The following code snippet explains how to create a context menu:

  public class MainActivity extends ListActivity 
  {
   private String selectedName = “”; 
  private String[] nameList; 
  @Override protected void onCreate(Bundle savedInstanceState) 
  { 
  super.onCreate(savedInstanceState);
   nameList = getResources ().getStringArray(R.array.name_list); 
  setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_ 1, nameList)); 
  registerForContextMenu (getListView()); 
  }
   @Override public boolean onCreateOptionsMenu (Menu menu) 
  { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate(R.menu.main, menu); 
  return true;
   }
   public void onCreateContextMenu (ContextMenu menu, View v, ContextMenuInfo menuInfo) 
  { 
  // Inflate the menu; this adds items to the action bar if it is present. 
  getMenuInflater().inflate (R.menu.main, menu); 
  }
  }

When the user selects an item within the context menu, the onContextItemSelected(MenuItem item) method gets executed. You can override this method to provide the functionality for the menu items, as shown in the following code snippet:

  public boolean onContextItemSelected (MenuItem item) 
  {
  AdapterContextMenuInfo adapInfo = (AdapterContextMenuInfo) item .getMenuInfo(); 
  selectedName = nameList[(int) adapInfo.id]; 
  switch (item.getItemId()) 
  { 
  case R.id.edit: 
  Toast.makeText(MainActivity.this, “You have pressed Edit Context Menu for” + selectedName, Toast.LENGTH_LONG).show(); 
  return true; 
  case R.id.del: 
  Toast.makeText(MainActivity.this, “You have pressed Delete Context Menu for” + selectedName, Toast.LENGTH_LONG).show(); 
  return true; 
  case R.id.linkc: 
  Toast.makeText(MainActivity.this, “You have pressed Link Contact Context Menu for” + selectedName, Toast.LENGTH_LONG).show(); 
  return true; 
  case R.id.markasdef: 
  Toast.makeText(MainActivity.this, “You have pressed Mark as Deafult Context Menu for ” + selectedName, Toast.LENGTH_LONG).show(); 
  return true; 
  case R.id.addtofav: 
  Toast.makeText(MainActivity.this, “You have pressed Add to Favorites Context Menu for ” + selectedName, Toast.LENGTH_LONG).show(); 
  return true; 
  } 
  return false; 
  } 
  }

The output of the preceding code is displayed, as shown in the following figure.

The
Context Menu

Figure 5 : The Context Menu

Creating Popup Menus

A popup menu uses a modal popup window to display a menu, which is anchored to a view. The popup appears below or above the anchor view as per the room available. It provides an overflow-style menu, a command sentence, and a drop-down list. The overflow-style menu provides an action related to a particular content, such as email headers of Gmail. The second part of a command sentence, such as the button marked Add, produces a popup menu with the different Add options. The drop-down list works like a spinner and does not maintain a persistent selection. To define your menu in XML, you need to perform the following tasks:

  1. Instantiate a popup menu with its constructor. It uses Context of the current app and View to which the menu should be anchored.
  2. Use MenuInflater to inflate your menu resource into the Menu object. This object is returned by a method named PopupMenu.getMenu(). However, you can use the PopupMenu.inflate()method for the API level 14 and above.
  3. Call PopupMenu.show().

The following code snippet describes the layout of a popup menu:

  <menu xmlns:android=“http:// schemas.android.com/apk/res/android” > <item android:id=“@+id/archive” android:title=“Save”/> <item android:id=“@+id/delete” android:title=“Delete”/> </menu>

The following code snippet describes how an activity can then show the popup menu:

public void showPopup(View v) 
  { 
  PopupMenu popup = new PopupMenu(this, v); 
  MenuInflater inflater = popup.getMenuInflater(); 
  inflater.inflate(R.menu.main, popup.getMenu()); 
  popup.show(); 
  }

When the user selects an item or touches outside the menu area, the menu gets dismissed. The menu dismiss event can be listened to by using PopupMenu.OnDismissListener. To perform an action after a user selects a menu item, you need to implement the PopupMenu.OnMenuItemClickListener interface and register it with PopupMenu by using setOnMenuItemclickListener(). The system calls the onMenuItemClick()callback when the user selects an item. The following code snippet describes the handling of the click events in a popup menu:

public void showMenu(View v) 
  { 
  PopupMenu popup = new PopupMenu(this, v); 
  // This activity implements OnMenuItemClickListener .
  popup.setOnMenuItemClickListener ((OnMenuItemClickListener) this); 
  popup.inflate(R.menu.main); 
  popup.show(); 
  } 
  public boolean onMenuItemClick(MenuItem item) 
  { 
  switch (item.getItemId()) 
  { 
  case R.id.archive: 
  archive(item);
  return true; 
  case R.id.delete: 
  delete(item);
  return true; 
  default: return false; 
  } 
  }

The output of the preceding code is displayed in the following figure.

The Popup
Menu

Figure 6: The Popup Menu

Customizing Views

There are various situations when the requirement of an app goes beyond the built-in views available. For example, you need to create a toggle button for an image being displayed as the background of your app. If the image is visible, the toggle button should hide it, and if the image is hidden, clicking on the button would make it visible. This toggle button is a custom view that you would need to create to fulfill the specific requirement of your app. By customizing views, the look and feel of an app can be changed completely. This further helps in creating UIs that are uniquely suited to a user’s need. One such way of implementing custom views is by creating compound views.

Creating Compound Views

Compound views refer to combining multiple views into a logical group of items that can be treated as a single view. An example of a compound view is a combo box, which is a combination of a single line edit text view, a button, and an attached pop-up list. If the user clicks the button and selects data from the list, it populates the edit text field with that data. The user can also type the data directly into the edit text field. Another example would be that you want to provide a text size slider to increase or decrease the font size of the text in your app. To create such a slider, you need to combine the text view widget with the seekbar widget, and then modify their functionality so that clicking on the seekbar changes the text in the text view. You can then use this compound control in any of your apps to provide a text size slider. Android provides two built-in compound views, spinner and AutoCompleteTextView. To create a compound view, you need to define the layout, appearance, and interaction of the views it contains. In Android, compound views are created by creating a class that extends the Layout class. The Layout class can be extended further, as shown in the following code snippet:

  public class MyCompoundView extends LinearLayout 
  { 
  public MyCompoundView (Context context, AttributeSet Attr) 
  { 
  super(context, Attr); 
  // TODO Auto-generated constructor stub. 
  } 
  }

Once you have extended your class, you can now use the views that you want to design the UI.

Conclusion

In this article we discussed creating Menus in android apps. We also explored the concept of Views in androids which helps developers manage Menus more effectively.



Certified Trainer for Windows 8 Mobile App Development, IBM CE Project Trainer With IBM DB2, RAD, RSA, Certified Trainer for ZEND (PHP), Certified PHP and MySql trainer, Certified trainer of Diploma in Oracle 10g (DBA) as per Orac...

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login