Android Program Development: (15th) Use menu -- 15.2 option menu

Source: Internet
Author: User

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.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.