Create OptionsMenu programmatically

OptionsMenu on ActionBar

 The options menu is the primary collection of menu items for an activity. The menu items are displayed on the ActionBar.

Step 1: In res/drawable/ directory add icons to be used in OptionsMenu. Take for example ic_add_white, ic_settings_white_24dp, and ic_info_outline_white.

Step 2: Open app/java/package and open MainActivity.java(or the relevant java file). To specify the options menu for the activity, override onCreateOptionsMenu(). In this method, add items to the Menu provided in the callback.

	@Override
    public boolean onCreateOptionsMenu(Menu menu)
    {
        // Add items to the OptionsMenu
        menu.add(0, 0, 0, "add").setIcon(R.drawable.ic_add_white).setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
		menu.add(0, 1, 0, "Settings").setIcon(R.drawable.ic_settings_white_24dp);
		menu.add(0, 2, 0, "Info").setIcon(R.drawable.ic_info_outline_white);
        return super.onCreateOptionsMenu(menu);
    }

Step 3: When the user selects an item from the options menu (including action items in the app bar), the system calls activity’s onOptionsItemSelected() method. This method passes the MenuItem selected. You can identify the item by calling getItemId() which returns the unique ID for the menu item, or by calling getTitle().toString() which returns the title for the menu item (defined by the android:id / android:title attribute in the menu resource). This ID or title can be matched against known menu items to perform the appropriate action.

@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		Intent i1 = new Intent();
                // TODO: Implement this method
		switch(item.getTitle().toString()){
			case "add":
				// Move to NewMemoActivity.java when 'add' icon is clicked
				i1.setClass(getApplicationContext(), NewMemoActivity.class);
				startActivity(i1);
			break;
			case "Info":
				// Move to InfoActivity.java when 'Info' icon is clicked
				i1.setClass(getApplicationContext(), InfoActivity.class);
			    startActivity(i1);
		    break;
			case "Settings":
				// Move to SettingsActivity.java when 'Settings' icon is clicked
				i1.setClass(getApplicationContext(), SettingsActivity.class);
			    startActivity(i1);
				break;
		}
		return super.onOptionsItemSelected(item);
	}

Output:
Now run the app. You will find the items defined in onCreateOptionsMenu on the ActionBar.

Leave a Reply