Learning android together (6)
The menu includes the OptionMenu, the context menu, and the SubMenu ).
To create a SubMenu:
1. Override the onCreateOptionMenu (Menu menu) method of the Activity. In this method, add a Menu through the Menu object method.
2. In response to the click event in the menu, override the onOptionItemSelected (MenuItem mi) method of the Activity.
The Code is as follows:
Public class MainActivity extends Activity {@ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_main) ;}@ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// create SubMenu subMenu1 = menu. addSubMenu ("sub menu 1"); // set the title of the menu header subMenu1.setHeaderTitle ("menu header Title 1"); // set the menu icon subMenu1.setIcon (R. drawable. ic_launcher); // set the icon subMenu1.setHeaderIcon (R. drawable. ic_launcher); // Add the menu item subMenu1.add (0, 0, 0, "menu item 1") to group 0; subMenu1.add (0, 1, 0, "menu item 2"); subMenu1.add (0, 2, 0, "menu item 3"); return true ;}@ Overridepublic boolean onOptionsItemSelected (MenuItem item) {// TODO Auto-generated method stubtoast (item. getTitle (); return super. onOptionsItemSelected (item);} private void toast (CharSequence title) {// TODO Auto-generated method stubToast. makeText (MainActivity. this, title, Toast. LENGTH_SHORT ). show ();}}
When you click Menu:
Click sub-menu 1: