Simple Menu Creation In Android

posted Jan 1, 2011, 7:48 AM by Thiyagaraaj M   [ updated Aug 20, 2011, 4:43 AM ]

Easy Stpes to menu creation in android
Menu Creation without XML in Android

Syntax For Menu Creation In Android:

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

Plan and Constant Values Declaration:

we plan create simple menu with four items.
then you declare four constant values in Java code 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;

Menu Creation Code:

and add menu creation code in onCreateOptionsMenu like this.
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");
}

Menu with Image:

if you want add image in menu. first you add icon images in drawable folder(name as menu_add,menu_edit).and you add setIcon with that drawable resource id.
menu.add(0, Option1, 1, "Test 2").setIcon(R.drawable.menu_add);
menu.add(0, Option2, 2, "Test 1").setIcon(R.drawable.menu_edit);

Sample Output:


Articles