Now we are ready to modify the items in the previous section. This way, when the user presses the menu button, it pops up.
1. Use the engineering in the previous section to add some code to the Menusactivity.java.
The public class Menusactivity extends activity {/** called the ' when ' is the ' The activity ' is the ' the '---' @Override
public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Button btn = (button) Findviewbyid (R.id.button1);
Btn.setoncreatecontextmenulistener (this); @Override public void Oncreatecontextmenu (ContextMenu menu, view view, Contextmenuinfo
Menuinfo) {Super.oncreatecontextmenu (menu, view, menuinfo);
CreateMenu (menu); @Override public boolean Oncreateoptionsmenu (Menu menu) {Super.oncreateoptionsmenu
(menu);
CreateMenu (menu);
return true; @Override public boolean onoptionsitemselected (MenuItem item) {return Men
Uchoice (item);
}
private void CreateMenu (Menu menu) {...}
Private Boolean Menuchoice (MenuItem item) {...} }
2. Press F11 to test on the simulator. The pop-up Options menu is shown below. Select a menu item or use a shortcut key (A through D). Note that the menu items from 1 to 3 do not display an icon, although we set the icon in the code.
3. If you set the Minimum SDK property to 10 (including 10) in Androidmanifest.xml, and then reload the program, you will see the icon. If there are too many menu items, a more option is displayed.
<USES-SDK android:minsdkversion= "Ten"/>
To display the option menu in an activity, you need to implement two methods: Oncreateoptionsmenu () and onoptionsitemselected (). The former is triggered when the menu key is clicked, and the latter is triggered when an item is clicked.
Note the style of the Options menu in different Android versions.
Back to the column page: http://www.bianceng.cnhttp://www.bianceng.cn/OS/extra/