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)
{
menu.add("Help");
return super.onCreateOptionsMenu(menu);
}

private void openOptionsHelpDialog()
{
new AlertDialog.Builder(this)
.setTitle(R.string.help_title).setMessage(R.string.help_message)
.setPositiveButton(R.string.help_ok,
new DialogInterface.OnClickListener() {

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

}
}
)
.show();
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
super.onOptionsItemSelected(item);
openOptionsHelpDialog();
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"?>
<resources>
<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>
<string name="help_ok">OK</string>
</resources>


Download the files.

No comments: