Adding a Menu

Android supports two kinds of menus. First, there is the menu you get when you press the physical Menu button. Second, there is a context menu that pops up when you press and hold your finger on the screen (or press and hold the trackball or the D-pad center button).

Let's do the first kind so that when the user presses the Menu key, they'll open a menu like the one in Figure 3.10. First we need to define a few strings that we'll use later:

Download Sudokuv1/res/values/strings.xml

<string name="settings_label">Settings...</string> <string name="settings_title">Sudoku settings</string> <string name="settings_shortcut">s</string> <string name="music_title">Music</string> <string name="music_summary">Play background music</string> <string name="hints_title">Hints</string>

<string name="hints_summary">Show hints during play</string> Then we define the menu using XML in res/menu/menu.xml:

Download Sudokuv1/res/menu/menu.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">

<item android:id="@+id/settings"

android:title="@string/settings_label"

android:alphabeticShortcut="@string/settings_shortcut" /> </menu>

Next we need to modify the Sudoku class to bring up the menu we just defined. To do that, we'll need a few more imports:

Download Sudokuv1/src/org/example/sudoku/Sudoku.java

import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem;

Report erratum

Then we override the Sudoku.onCreateOptionsMenu() method:

Download Sudokuvl/src/org/example/sudoku/Sudoku.java

@Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); Menulnflater inflater = getMenuInflater(); inflater.inflate(R.menu.menu, menu); return true;

getMenuInflater() returns an instance of Menulnflater that we use to read the menu definition from XML and turns it into a real view. When the user selects any menu item, onOptionsItemSelected() will be called. Here's the definition for that method:

Download Sudokuvl/src/org/example/sudoku/Sudoku.java

@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.settings:

startActivity(new Intent(this, Prefs.class)); return true;

return false;

Prefs is a class that we're going to define that displays all our preferences and allows the user to change them.

0 0

Post a comment