Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.java.programmer > #4045
| From | Lawrence D'Oliveiro <ldo@geek-central.gen.new_zealand> |
|---|---|
| Newsgroups | comp.lang.java.programmer |
| Subject | Building The Android Options Menu |
| Followup-To | comp.lang.java.programmer |
| Date | 2011-05-13 22:52 +1200 |
| Organization | Geek Central |
| Message-ID | <iqj2h8$i4u$1@lust.ihug.co.nz> (permalink) |
Followups directed to: comp.lang.java.programmer
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>.
Back to comp.lang.java.programmer | Previous | Next | Find similar
Building The Android Options Menu Lawrence D'Oliveiro <ldo@geek-central.gen.new_zealand> - 2011-05-13 22:52 +1200
csiph-web