1. Create Project

Select File -> New -> Other -> Android -> Android Project and create the Android project “com.mobisys.android.menu_example”. Enter the following.

2. Add a menu XML resource

Select your project, right click on it and select New -> Other -> Android -> Android XML File to create a new XML resource.

Select the option “Menu”, enter as File name as “ex_menu.xml” and press the button “Finish”.

This will create a new file “ex_menu.xml” in the folder “res/menu” of your project. To make changes to ex_menu.xml file, switch to xml view & replace with the following code.

<?xml version="1.0" encoding="utf-8"?>

      <item android:id="@+id/next"
              android:title="next" />
      <item android:id="@+id/previous"
            android:title="previous" />

You see that the Menu root node consists of 3 item leaf nodes. Each of the items consists
of an id, icon and title. The resource id is unique to that item and it allows the
application to recognize which item has been clicked by the user. The icon is a drawable
that should exist in the res/drawable folder and is the one shown in the menu item.
The string is the item’s title.

The above assumes that you have two images ic_next, ic_previous into the drawable folder. It goes without saying that these image sizes should be kept as small as possible.

Now, we need to override the method: onCreateOptionsMenu(Menu menu) in MenuActivity class. This method is called by Android the first time the activity is loaded. Here is the code:

    public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.ex_menu, menu);
      return true;

This method is getting a handle to the MenuInflater and using it to inflate the options menu that we have defined earlier in ex_menu.xml in the res/menu folder.
Now, that the menu is created, how do we respond to the user when he clicks on the menu. This is done by overriding the onOptionsItemSelected(MenuItem item) method in the Activity itself as shown below:

public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.next:
    		Toast.makeText(this, "You have chosen the Next menu option", Toast.LENGTH_SHORT).show();
    	case R.id.previous:
    		Toast.makeText(this, "You have chosen the Prev. menu option", Toast.LENGTH_SHORT).show();
    		return super.onOptionsItemSelected(item);

So, within this method,

We check which item has been clicked by retrieving the item id through item.getItemId(). Then we use the switch statement to take action based on the id. If it is R.id.next that has been selected, then we toast a message that the “Next” menu option has been selected.Similarly we toast message for “previous”.

3. Output Screen

Output Screen is shown as below:

Click here to download the source code

AUTHOR: Vikas Hiran
No Comments

Leave a Comment

Your email address will not be published.