Monday, December 14, 2009

Implement a Help Dialog, using onCreateOptionsMenu(), onOptionsItemSelected() and AlertDialog.Builder.

Follow the code from previouse exercise, Move the marker on MapView with Zoom Control Seekbar.
In this exercise, a OptionsMenu with a single OptionsItem of help will be added.

The option items is added to the option menu in the method onCreateOptionsMenu(), in which initialize the contents of the Activity's standard options menu.

Because it's only one item in the menu, Menu.add(CharSequence title) is used to add item to the menu. Otherwise, Menu.add(int groupId, int itemId, int order, CharSequence title) or Menu.add(int groupId, int itemId, int order, int titleRes) have to be used.

onOptionsItemSelected() will be called whenever an item in options menu is selected. Also, because it's only one item in the menu, so there are no need to check which item have been selected, otherwise, you have to check the itemId.

Add the following three method in the class AndroidMapView:
 public boolean onCreateOptionsMenu(Menu menu)
return super.onCreateOptionsMenu(menu);

private void openOptionsHelpDialog()
new AlertDialog.Builder(this)
new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub


public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
return true;

Implement a file helpmessage.xml in the folder /res/values/, it's used to hold the text used inside the Help Dialog.
<?xml version="1.0" encoding="utf-8"?>
<string name="help_title">Help!</string>
<string name="help_message">\n
Pan on the Map: touch the screen and move.\n
Update location: touch on the screen.\n
Zoom: slice on the SeekBar on bottom.\n
<string name="help_ok">OK</string>

Download the files.

No comments: