Creating and Displaying Menus
In this lesson we learn how to create a basic context menu.
When the user presses on the Menu button, your app should present a "Context Menu." Even our simple app could use some context help. In this section, you will learn how to add a context menu with three panes: Manage Key | Options | About. First add a folder "menu" in the res folder by right clicking over the res folder and selecting New --> Folder. With this new folder as your selection, add a new file menu.xml by choosing New--> AndroidXMLFile and name the file confusetext_menu.xml. Here is the XML code for our context menu without icons:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/manage_password"
android:title="@string/manage_password"/>
<item android:id="@+id/options"
android:title="@string/options"/>
<item android:id="@+id/about"
android:title="@string/about"/>
</menu>
Now you will need to edit the strings.xml file by adding in the following lines of XML.
<string name="manage_password">Manage Key</string>
<string name="about">About</string>
<string name="options">Options</string>
These XML files describe the presentation of the context menu. To trap the system event that is fired when the user presses on the menu button while this app has the focus, add the following Java code to the ConfuseText.java file:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater= getMenuInflater();
inflater.inflate(R.menu.confusetext_menu, menu);
return true;
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Finally, add the necessary imports to ConfuseText.java:
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
I copied some of the previous code for onCreate to help you place the onCreateOptionsMenu method. Now, when the user clicks on the menu button and ConfuseText has the focus, the following context menu appears:
Now when the user clicks on one of the three choices in the context message, we trap the event in the onOptionsItemSelected method as in:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.manage_password:
;
return true;
case R.id.options:
;
return true;
case R.id.about:
this.showDialog(DIALOG_ABOUT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
This method does not do much of anything! Next we will create an alert dialog for use when the user selects "About." But first, add the following three constants to the java file:
private static final int MANAGE_PASSWORD= 0;
private static final int OPTIONS= 1;
private static final int DIALOG_ABOUT= 2;
That should get rid of those nasty error warnings.
Have fun,
JAL