Using menu options, you need to do the following:
(1) Rewriting the Oncreateoptionsmenu method;
Public Boolean returntrue;}
(2) Add the item's declaration to the Main.xml file in menu.
(3) Overriding the onoptionsitemselected method
Public Boolean Switch (Item.getitemid ()) { case item1: break; Case item2: break; ... default :} return true ;}
The sample code mimics the first line of code
(1) The code for Menudemo.java is as follows:
Public classMainactivityextendsActivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Requestwindowfeature (Window.feature_no_title); //eliminate the title barSetcontentview (R.layout.activity_main); } @Override Public BooleanOncreateoptionsmenu (Menu menu) {//inflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true; } //defining Menu Response Events Public Booleanonoptionsitemselected (MenuItem item) {Switch(Item.getitemid ()) { CaseR.id.riven:toast.maketext ( This, "The day of the Broken sword recasting, the time of its return!", Toast.length_short). Show (); Break; CaseR.id.ezreal:toast.maketext ( This, "It's time to perform the real technology!", Toast.length_short). Show (); Break; default: } return true; } }
(2) Activity_main.xml in layout:
< TextView Android:layout_width = "Wrap_content" android:layout_height= "Wrap_content" android:text= "Welcome to Summoner Canyon!" \ n Click the menu key to display the menu option "/>
(3) The Main.xml code in the menu:
<Menuxmlns:android= "Http://schemas.android.com/apk/res/android" > <ItemAndroid:id= "@+id/riven"android:orderincategory= "+"android:showasaction= "Never"Android:title= "The Edge of Exile Rui Wen"/> <ItemAndroid:id= "@+id/ezreal"android:orderincategory= "+"android:showasaction= "Never"Android:title= "@string/ezreal"/></Menu>
(4) in the string.xml of values, define a string constant.
<?XML version= "1.0" encoding= "Utf-8"?><Resources> <stringname= "App_name">Menudemo</string> <stringname= "Action_settings">Settings</string> <stringname= "Hello_world">Hello world!</string> <stringname= "Ezreal">Explorer Ezreal</string></Resources>
The code works as follows:
When you click the menu option, it appears as follows:
Android Notes: Menu