Creating a Menu

In the Android SDK, you don't need to create a menu object from scratch. Because an activity is associated with a single menu, Android creates this single menu and passes it to the onCreateOptionsMenu callback method. (As the name of the method indicates, menus in Android are also known as options menus.) This method allows you to populate the menu with a set of menu items (see Listing 5-1).

Listing 5-1. Signature for the onCreateOptionsMenu Method ^Override public boolean onCreateOptionsMenu(Menu menu) {

// populate menu items ...return true;

Once the menu items are populated, the code should return true to make the menu visible. If this method returns false, the menu becomes invisible. The code in Listing 5-2 shows how to add three menu items using a single group ID along with incremental menu-item IDs and sort-order IDs.

Listing 5-2. Adding Menu Items ^Override public boolean onCreateOptionsMenu(Menu menu) {

//call the base class to include system menus super.onCreateOptionsMenu(menu);

0 0

Post a comment