How to Dynamically or Programmatically Add Menu Items for an Android Activity

Published by Igor Khrupin on

2017-03-04-17-25-56

Sometimes you don’t need huge menu. And int is’t super important create XML file for it.

You can just create your menu from code. It is very simple.

You need override `

public boolean onPrepareOptionsMenu(Menu menu)

` method. Let’s see the example below:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    menu.clear();
    menu.add(0, MENU_EDIT, Menu.NONE, getString(R.string.menu_action_edit)).setIcon(R.drawable.ic_action_edit).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    menu.add(0, MENU_DELETE, Menu.NONE, getString(R.string.menu_action_delete)).setIcon(R.drawable.ic_action_delete).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
    return super.onPrepareOptionsMenu(menu);
}

Here is you have created two menu items “Edit” and “Delete”. This menu items has showAsAction `

MenuItem.SHOW_AS_ACTION_ALWAYS

`. You can change it for your requirements. Also you can group menu items. For example my menu items in group with id = 0.

Also you can handle menu click actions. It is pretty same to XML menus. Let’s see:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case MENU_EDIT:
            Toast.makeText(this, "Edit menu item clicked", Toast.LENGTH_SHORT).show();
            break;
        case MENU_DELETE:
            Toast.makeText(this, "Delete menu item clicked", Toast.LENGTH_SHORT).show();
            break;
    }
    return false;
}

As you can see it is very simple. You don’t need addition files in your project for just two menus. Use this approach.

Hope it help you.

Also here is link to github project.

Download it from github

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.