Previously, I have discussed how to create a menu item in an article. However, this method is inefficient and difficult to maintain. Now, another method is used to create a menu.
MenuInflater. With this class, you can easily create menu items as follows:
1. In the res/menu/folder, find the main. xml file, which is the place where menu items are defined. Add the following menu items to some files:
Copy codeThe Code is as follows: <item
Android: id = "@ + id/menu1"
Android: icon = "@ android: drawable/alert_dark_frame"
Android: title = "Menu1"/>
<Item
Android: id = "@ + id/menu2"
Android: icon = "@ android: drawable/alert_dark_frame"
Android: title = "Menu2"/>
<Item
Android: id = "@ + id/menu3"
Android: icon = "@ android: drawable/alert_dark_frame"
Android: title = "Menu3"/>
<Item
Android: id = "@ + id/menu4"
Android: icon = "@ android: drawable/alert_dark_frame"
Android: title = "Menu4"/>
2. Override the following method in the Activity and add a method to display the system settings interface.Copy codeThe Code is as follows: @ Override
Public boolean onCreateOptionsMenu (Menu menu ){
MenuInflater inflater = getMenuInflater ();
Inflater. inflate (R. menu. main, menu );
Return true;
}
@ Override
Public boolean onOptionsItemSelected (MenuItem item ){
Switch (item. getItemId ()){
Case R. id. menu1: // in some cases, define the RESPONSE event of the first menu item.
Break;
Case R. id. menu2:
Break;
Case R. id. menu3:
Break;
Case R. id. menu4:
ShowSettings ();
Break;
}
Return super. onOptionsItemSelected (item );
}
Private void showSettings (){
Final Intent settingsIntent = new Intent (android. provider. Settings. ACTION_SETTINGS );
SettingsIntent. setFlags (Intent. FLAG_ACTIVITY_NEW_TASK | Intent. FLAG_ACTIVITY_RESET_TASK_IF_NEEDED );
StartActivity (settingsIntent );
}
3. Run the program and click Menu. The following results will be displayed:
Click Menu4. The system settings page is displayed!