The Menu

The final aspect of application control we'll cover in this chapter is the menu. Example 10-14 shows how to implement a simple menu by overriding two Activity methods.

Example 10-14. Implementing a menu

^Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(Menu.NONE, CLEAR_MENU_ID, Menu.NONE, "Clear"); return true;

^Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 1:

dotModel.clearDots(); return true;

default: ;

return false;

When this code is added to the TouchMe class, clicking the device's Menu key will cause the application to present a menu (labeled "Clear" at the bottom of the screen), as shown in Figure 10-7.

Figure 10-7. A simple menu

Clicking the Enter key or tapping the menu item again will clear the dot widget.

Interestingly, if you run this application, you will find that while the added menu item works most of the time, it does not work when the DotView is in focus. Can you guess why?

If you guessed that the problem is caused by the OnKeyListener installed in the DotView, you are correct! As implemented in Example 10-15, the listener swallows the menu key event by returning true when it is clicked. This prevents the standard View processing of the menu key keystroke. In order to make the menu work, the OnKey Listener needs a new case, shown in Example 10-15.

Example 10-15. Improved key handling switch (keyCode) {

case KeyEvent.KEYCODE_MENU:

The Android UI framework also supports contextual menus. A ContextMenu appears in response to a long click in a widget that supports it. The code required to add a contextual menu to an application is entirely analogous to that for the options menu shown earlier except that the respective methods are onCreateContextMenu and onContextItemSelected. Additionally, one more call is required. In order to support contextual menus, a widget must be assigned a View.OnCreateContextMenuListener by calling its View method, setOnCreateContextMenuListener. Fortunately, since Activity implements the View.OnCreateContextMenuListener interface, a common idiom looks like Example 10-16.

Example 10-16. Installing a ContextMenuListener findViewById(;

Simply overriding the default, empty Activity implementations of the context menu listener methods will give your application a context menu.

This chapter has shown how the Android graphical interface works overall, and has given you the tools to manipulate its basic components: windows, Views, and events. The following chapter explains the most useful widgets Android makes available, and Chapter 12 shows you how to do your own graphics programming.


Was this article helpful?

0 0

Post a comment