One, Optionsmenu options menu
Clicking on the Function button in the application will bring up the Options menu, click to achieve the specific function.
Second, the realization of ideas:
1. Create Options Menu: Oncreateoptionsmenu ();
2, set menu items can be dynamically set menu.add (), and also through XML Settings Menuinflater.infalte (R.menu.menu);
3. Set Menu click event: Onoptionsitemselect ();
Three, the sample code:
Custom Menu xml:
<Menuxmlns:android= "Http://schemas.android.com/apk/res/android"Xmlns:app= "Http://schemas.android.com/apk/res-auto"Xmlns:tools= "Http://schemas.android.com/tools"Tools:context=". Mainactivity "> <ItemAndroid:id= "@+id/action_settings1"android:orderincategory= "+"Android:title= "Menu 1"app:showasaction= "Never" /> <ItemAndroid:id= "@+id/action_settings2"android:orderincategory= "$"Android:title= "Menu 2"app:showasaction= "Never" /></Menu>
Androidmanifest.xml config file, add a new page
< Activity Android:name =". Menuactivity " android:label=" Menu Settings page "></activity >
Mainactivity.java Background code files
PackageCom.example.zhengcheng.optionsmenudemo;Importandroid.content.Intent;Importandroid.support.v7.app.ActionBarActivity;ImportAndroid.os.Bundle;ImportAndroid.view.Menu;ImportAndroid.view.MenuItem;ImportAndroid.widget.Toast; Public classMainactivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//to load a menu in an XML file//getmenuinflater (). Inflate (R.menu.menu_main, menu); //adding menus dynamicallyMenu.add (1,101,1, "Menu 1"); Menu.add (1,102,1, "Menu 2"); Menu.add (1,103,1, "Menu 3"); Menu.add (1,104,1, "Menu 4"); Menu.add (1,105,1, "menu 5"); return true; } @Override Public Booleanonoptionsitemselected (MenuItem item) {intID =Item.getitemid (); //get which menu item is clicked on the page//switch (ID) {//Case R.ID.ACTION_SETTINGS1://Toast.maketext (This, "clicked Menu 1", Toast.length_short). Show ();//Break ;//Case R.ID.ACTION_SETTINGS2://Toast.maketext (This, "clicked Menu 2", Toast.length_short). Show ();//Break ;// } //get a dynamically generated menu item Switch(ID) { Case101: //Click on the menu to open a new pageIntent Intent =NewIntent (mainactivity. This, Menuactivity.class); Item.setintent (Intent); Break; Case102: Toast.maketext ( This, "clicked Menu 2", Toast.length_short). Show (); Break; Case103: Toast.maketext ( This, "clicked Menu 3", Toast.length_short). Show (); Break; Case104: Toast.maketext ( This, "clicked Menu 4", Toast.length_short). Show (); Break; Case105: Toast.maketext ( This, "clicked Menu 5", Toast.length_short). Show (); Break; } return Super. onoptionsitemselected (item); }}
Android Learning (21) Optionsmenu Options Menu