Pr.Pg Next Pg

Options Menu tutorials

 

Defining a Menu in XML

  • For all menu types, Android provides a standard XML format to define menu items. Instead of building a menu in your activity's code, you should define a menu and all its items in an XML menu resource. You can then inflate the menu resource (load it as a Menu object) in your activity or fragment.

  • Using a menu resource is a good practice for a few reasons:

  • It's easier to visualize the menu structure in XML.

  • It separates the content for the menu from your application's behavioral code.

  • It allows you to create alternative menu configurations for different platform versions, screen sizes, and other configurations by leveraging the app resources framework.

  • To define the menu, create an XML file inside your project's res/menu/ directory and build the menu with the following elements:

  • <menu>

  • Defines a Menu, which is a container for menu items. A <menu> element must be the root node for the file and can hold one or more <item> and <group> elements.

  • <item>

  • Creates a MenuItem, which represents a single item in a menu. This element may contain a nested <menu>element in order to create a submenu.

  • <group>

  • An optional, invisible container for <item> elements. It allows you to categorize menu items so they share properties such as active state and visibility.

  • The <item> element supports several attributes you can use to define an item's appearance and behavior. The items in the above menu include the following attributes:

  • android:id

  • A resource ID that's unique to the item, which allows the application can recognize the item when the user selects it.

  • android:icon

  • A reference to a drawable to use as the item's icon.

  • android:title

  • A reference to a string to use as the item's title.

  • android:showAsAction

  • Specifies when and how this item should appear as an action item in the action bar.

  • These are the most important attributes you should use, but there are many more available.

  • The Options Menu when created will somehow look like this.

 

 

Pr.Pg border                                              Next Pg