Home>

There are many ways to add menus,It is generally recommended to create menus using xml.

Create menu steps:

Create a menu folder under res, and add an xml file in the menu file:

<?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 menu to application:

How to add a defined menu when the application starts?In the oncreateoptionsmenu () event, use the menuinflater to add the defined menu to the application:

@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 point, the menu has been added to the application,But there is still a problem,The current menu is just displayed,Did not handle the message that triggered the menu,You can use the onoptionsitemselected () event to customize message processing.The following is a menu implementation for stopping and playing music, respectively:

@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:

  • Previous Waterfall effect with jQuery scroll down to load content instantly
  • Next Understanding of objects and references and inner classes in Java's object-oriented programming