Incorporating Anonymous Actions in Your Activitys Menu

To add Menu Items to your Menus dynamically at run time, use the addIntentOptions method on the Menu object in question: pass in an Intent that specifies the data for which you want to provide actions. Generally this will be handled within your Activities' onCreateOptionsMenu or onCreateContextMenu handlers.

The Intent you create will be used to resolve components with Intent Filters that supply actions for the data you specify. The Intent is being used to find actions, so don't assign it one; it should specify only the data to perform actions on. You should also specify the category of the action, either CATEGORY_ALTERNATIVE or CATEGORY_SELECTED_ALTERNATIVE.

The skeleton code for creating an Intent for menu-action resolution is shown here:

Intent intent = new Intent();



Pass this Intent in to addIntentOptions on the Menu you wish to populate, as well as any option flags, the name of the calling class, the menu group to use, and the menu ID values. You can also specify an array of Intents you'd like to use to create additional menu items.

Listing 5-11 gives an idea of how to dynamically populate an Activity menu that would include the ''moon-base nuker'' action from Listing 5-10.

LISTING 5-11: Dynamic Menu population from advertised actions

Available for @Override download on public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu);

// Create the intent used to resolve which actions

// should appear in the menu.

Intent intent = new Intent();



// Normal menu options to let you set a group and ID

// values for the menu items you're adding.

int menuGroup = 0;

int menuItemId = 0;

int menuItemOrder = Menu.NONE;

// Provide the name of the component that's calling // the action -- generally the current Activity. ComponentName caller = getComponentName();

// Define intents that should be added first. Intent[] specificIntents = null;

// The menu items created from the previous Intents // will populate this array. MenuItem[] outSpecificItems = null;

// Set any optional flags.

int flags = Menu.FLAG_APPEND_TO_GROUP;

// Populate the menu menu.addIntentOptions(menuGroup, menuItemId, menuItemOrder, caller, specificIntents, intent, flags, outSpecificItems);

return true;

Was this article helpful?

0 0
Mobile Apps Made Easy

Mobile Apps Made Easy

Quick start guide to skyrocket your offline and online business success with mobile apps. If you know anything about mobile devices, you’ve probably heard that famous phrase coined by one of the mobile device’s most prolific creators proclaiming that there’s an app for pretty much everything.

Get My Free Training Guide

Post a comment