+ Reply to Thread
Results 1 to 2 of 2

Thread: How to Create Menu in Android ?

  1. #1
    Junior Member
    Join Date
    Aug 2012
    Posts
    15

    How to Create Menu in Android ?

    I have been using fixed xml layout for menu but it would be great to know how to create a options menu in android.

    Thanks in advance.

  2. #2
    Menus offer a way to expose application functions without loosing valuable screen space

    To define a menu for an Activity, override its onCreateOptionsMenu handler which receives a Menu object as a parameter,Inflate the menu layout file

    Code:
    @Override
        public boolean onCreateOptionsMenu(Menu menu)
        {
            MenuInflater menuInflater = getMenuInflater();
            menuInflater.inflate(R.layout.menu, menu);
            return true;
        }

    You can define your Menu hierarchies as XML resources.I have used the following XML snippet.
    Add this code in menu.xml under res/layout by creating a new xml file named menu.xml

    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <!-- Single menu item
             Set id, icon and Title for each menu item
        -->
        <item android:id="@+id/About"
              android:icon="@drawable/ic_launcher"
              android:title="About" />
        <item android:id="@+id/Tutorial"
              android:icon="@drawable/ic_launcher"
              android:title="Tutorial" />
        <item android:id="@+id/Credits"
              android:icon="@drawable/ic_launcher"
              android:title="Credits" />
        <item android:id="@+id/Share"
              android:icon="@drawable/ic_launcher"
              android:title="Share" />
        <item android:id="@+id/Submenu"
              android:icon="@drawable/ic_launcher"
              android:title="Submenu">
              <menu>
                <item
                    android:id="@+id/submenu_1"
                    android:title="Sub Menu 1" />
                </menu></item>
        <item android:id="@+id/Settings"
              android:icon="@drawable/ic_launcher"
              android:title="Basic Settings" />
        
        <item android:id="@+id/Settings2"
              android:icon="@drawable/ic_launcher"
              android:title="Advanced Settings" />
      
    </menu>
    Android handles menu item selections using the onOptionsItemSelected method and the menu item selected is passed in to this method as the MenuItem parameter.

    Code:
    public boolean onOptionsItemSelected(MenuItem item)
        {
            switch (item.getItemId())
            {
            case R.id.About:
               // perform menu handler actions
         }
    }

+ Reply to Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts