Now, we can modify the project in the previous section. In this way, the option menu will pop up when you press the menu key.
1. Use the project in the previous section and add some code in MenusActivity. java.
[Java]
Public class MenusActivity extends Activity {
/** Called when the activity is first created .*/
@ 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 MenuChoice (item );
}
Private void CreateMenu (Menu menu)
{
......
}
Private boolean MenuChoice (MenuItem item)
{
......
}
}
2. Press F11 to test the simulator. The options menu is displayed below. Select A menu item or use the shortcut key (A to D ). Note that the menu items from 1 to 3 do not show icons, even though we have set icons in the code.
3. If you set the minimum SDK attribute below 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.
[Java]
<Uses-sdk android: minSdkVersion = "10"/>
To display the option menu in the 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 a MENU item is clicked.
Pay attention to the style of the option menu in different android versions.