Building The Android Options Menu

  • Thread starter Lawrence D'Oliveiro
  • Start date
L

Lawrence D'Oliveiro

Handling the menu that an activity pops up when the user presses the Menu
button normally requires two stages: 1) put all the items into the menu 2)
respond to a menu selection and invoke the appropriate action.

I came up with a way of combining most of the work of the two into one
stage. I build a table that maps menu items into Runnable objects that
perform the corresponding action:

java.util.Map<android.view.MenuItem, Runnable> OptionsMenu;

Then my onCreateOptionsMenu method builds the menu and attaches the actions
in a single sequence, something like this:

@Override
public boolean onCreateOptionsMenu
(
android.view.Menu TheMenu
)
{
OptionsMenu = new java.util.HashMap<android.view.MenuItem, Runnable>();
OptionsMenu.put
(
TheMenu.add(R.string.show_calc_help),
new Runnable()
{
public void run()
{
startActivity
(
new android.content.Intent
(
android.content.Intent.ACTION_VIEW,
android.net.Uri.fromParts
(
"file",
"/android_asset/help/index.html",
null
)
).setClass(Main.this, Help.class)
);
} /*run*/
} /*Runnable*/
);
OptionsMenu.put
(
TheMenu.add(... another string ...),
new Runnable()
{
public void run()
{
... another action ...
} /*run*/
} /*Runnable*/
);
... more OptionsMenu.put calls for more items ...
return
true;
} /*onCreateOptionsMenu*/

And the actual handler for item selections can be this simple generic
routine:

@Override
public boolean onOptionsItemSelected
(
android.view.MenuItem TheItem
)
{
boolean Handled = false;
final Runnable Action = OptionsMenu.get(TheItem);
if (Action != null)
{
Action.run();
Handled = true;
} /*if*/
return
Handled;
} /*onOptionsItemSelected*/

For a full example of this technique in operation (and a similar one for
handling results from sub-activities), see
<https://github.com/ldo/ti5x_android/blob/master/src/Main.java>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,480
Members
44,900
Latest member
Nell636132

Latest Threads

Top