There are many ways to add menus. We generally recommend using xml to create menus.
To create a menu:
Create a menu folder under res and add an xml file to the menu file:
[Html] <? Xml version = "1.0" encoding = "UTF-8"?>
<Menu xmlns: android = "http://schemas.android.com/apk/res/android">
<Item android: id = "@ + id/play"
Android: title = "Play"
Android: visible = "true"/>
<Item android: id = "@ + id/stop"
Android: title = "Stop"
Android: visible = "true"/>
</Menu>
<? Xml version = "1.0" encoding = "UTF-8"?>
<Menu xmlns: android = "http://schemas.android.com/apk/res/android">
<Item android: id = "@ + id/play"
Android: title = "Play"
Android: visible = "true"/>
<Item android: id = "@ + id/stop"
Android: title = "Stop"
Android: visible = "true"/>
</Menu>
Add the menu to the application:
How do I add the defined menu when starting with a program? In the onCreateOptionsMenu () event, use MenuInflater to add the defined menu to the application:
[Java] @ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater ();
Inflater. inflate (R. menu. options_menu, menu );
Return true;
}
@ Override
Public boolean onCreateOptionsMenu (Menu menu ){
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater ();
Inflater. inflate (R. menu. options_menu, menu );
Return true;
}
At this time, the menu has been added to the application, but there is another problem, the current menu is only displayed, and does not process the trigger menu message, then you can use onOptionsItemSelected () event comes from defining message processing. The following is a menu implementation for stopping and playing music:
[Java] @ Override
Public boolean onOptionsItemSelected (MenuItem item ){
// TODO Auto-generated method stub
Int item_id = item. getItemId ();
Switch (item_id ){
Case R. id. play:
Intent intent = new Intent (WebTestActivity. this, yypService. class );
StartService (intent );
Break;
Case R. id. stop:
This. onStop ();
Break;
Default:
Return false;
}
Return true;
}
@ Override
Public boolean onOptionsItemSelected (MenuItem item ){
// TODO Auto-generated method stub
Int item_id = item. getItemId ();
Switch (item_id ){
Case R. id. play:
Intent intent = new Intent (WebTestActivity. this, yypService. class );
StartService (intent );
Break;
Case R. id. stop:
This. onStop ();
Break;
Default:
Return false;
}
Return true;
}
The program effect is as follows:
From Young's column