Create A Menu : Android Programming

In the previous post i have explain you about how to create a simple button for android devices and if you missed that then read it:

Read: How to Create a Simple Button Control – Android Programming

Now moving ahead to this and today we are going to program one of the used feature called Menus which you saw used it in many apps and this control gives the user to better navigation power. Android also offers a syntax and keywords which is available in Android SDK and its documentation.

Now to create a Menu in android here is the syntax:

menu.add(groupId, itemId, order, titleRes);

  • groupid: Your app may have more than one menus then group menus can be used to separate the common menu items.(0,1..n).
  • ItemId: Each content in menu is considered as itemId. Give value like 1 ,2,3 for indexing.
  • order: Which menu to display first and then second. Default is order of creation but you can change it.
  • titleres: Title of Menu or caption.

Now to create a menu we have to use a constructor onCreateOptionsMenu(Menu var1) which is available in Android SDK. Here refer the code for it.

public boolean onCreateOptionsMenu(Menu menu)

{

menu.add(0, Option1, 1, “Test 2”).setIcon(R.drawable.menu_add);

menu.add(0, Option2, 2, “Test 1”).setIcon(R.drawable.menu_edit);

menu.add(0, Option3, 3, “Test 3”);

menu.add(0, Option4, 4, “Test 4”);

}

Here i pass the item id a declared constant variable. Like this:

public static final int Option1 = 1;

public static final int Option2  = 2;

public static final int Option3 = 3;

public static final int Option4 = 4;

but you can pass the numeric value directly like 1,2,3,4 but for better programming practice this is the standard way.

If you noticed then i used setIcon(R.drawable.menu_add); in the above code. This code is responsible for placing image with the menu where R.Drawable is the static function which we used to create the image.

This is the sample output by assuming that you know how to run this and if not then read our post for android basics.

Thank you and Happy programming.

About Shahid

Shahid is a Engineering student and addicted to Technology. He is Working For iTechCode(Editor-In-Chief) very passionate about blogging and technology. His area of interest includes programming, tech gadgets, gaming, internet marketing, blogging etc.

Comments

  1. Rizwan Sultan says:

    Hey Shahid,
    I don’t have experience for android programming but I am really crazy too learn that professionally I am working in php based application development.

  2. Oh it looks You are master in C and C++………..!!
    :P:P

Speak Your Mind

*