Recipe Defining Menus in XML

Menus can also be built in XML and inflated with the appropriate callback method from the previous recipe.This is a useful context for larger menus. Dynamic choices can still be handled in Java.

Menu files are usually kept in the res/menu/ resources directory. For example, to make the context menu from the previous chapter, just create the XML file with nested menus, as shown in Listing 5.4.

Listing 5.4 res/menu/context_menu.xml

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

<menu xmlns:android=""> <item android:id="@+id/submenu" android:title="Change Text"> <menu xmlns:android=""> <item android:id="@+id/text1" android:title="Press Me" /> <item android:id="@+id/text2" android:title="Try Again" /> <item android:id="@+id/text3" android:title="Change Me" /> </menu> </item>

<item android:id="@+id/orig" android:title="Original Text" /> </menu>

Then, inflate this XML in the creation of the menu, and reference the IDs from the item selection method. The two methods in Listing 5.2 that would be replaced are shown in Listing 5.5.

Listing 5.5 Changed Methods in the Main Activity

@Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); Menulnflater inflater = getMenuInflater(); inflater.inflate(, menu);

@Override public boolean onContextItemSelected(MenuItem item) { switch(item.getItemId()) { case

bv.setText(R.string.hello); return true; case

bv.setText(choices[0]); return true; case


return true; case

bv.setText(choices[2]); return true;

return super.onContextItemSelected(item);

Character Building Thought Power

Character Building Thought Power

Character-Building Thought Power by Ralph Waldo Trine. Ralph draws a distinct line between bad and good habits. In this book, every effort is made by the writer to explain what comprises good habits and why every one needs it early in life. It draws the conclusion that habits nurtured in early life concretize into impulses in future for the good or bad of the subject.

Get My Free Ebook

Post a comment