Android programming Implementation To add a menu to the application of the method _android

Source: Internet
Author: User
Tags stub

This article describes the Android programming implementation to add a menu to the application method. Share to everyone for your reference, specific as follows:

There are many ways to add menus, and it is generally recommended that you create menus with XML.

To establish the menu step:

Create a menu folder under Res and add an XML file inside 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>

To add a menu to an application:

How do I add a defined menu when the application starts? In the Oncreateoptionsmenu () event, use the Menuinflater to add the defined menu to the program:

@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 a problem, now the menu is only displayed, and does not handle the trigger menu message, then you can use the onoptionsitemselected () event to customize message processing , The following is a menu implementation that stops and plays music:

@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 effect of the program is as follows:

I hope this article will help you with the Android program.

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.