Creating Options Menu in Android Application || Android Options Menu Sample/Example

Hi in this tutorial lets see how to create a options menu in Android.

1. create a new android application or use any of your existing application. for creating a options menu in android go to project in the package explorer and locate res folder inside that go to menu folder there you will get the main.xml file.

2. In main.xml file we will add our menu items.

 <menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:id="@+id/menu1"
          android:title="@string/menu1" >
    </item>
  
   <item android:id="@+id/menu2"
          android:title="@string/menu2" >
        <!-- submenu -->
        <menu>
            <item android:id="@+id/sub1_menu2"
                  android:title="@string/sub1_menu2" />
            <item android:id="@+id/sub2_menu2"
                  android:title="@string/sub2_menu2" />
        </menu>
    </item>

</menu>

here in the above example we are creating a menu 1 and menu 2 .. and menu 2 is having futher two submenus




3. Now go to src folder and mainActivity.java page, here we will add method for implementing action after clicking those menus.

Now in this application we will just try to show a message to the user that the menu has been clicked.

    public boolean onOptionsItemSelected(MenuItem item) {
     
        switch (item.getItemId()) {
            case R.id.menu1:
                Toast.makeText(getApplicationContext(), "this is menu1",
                           Toast.LENGTH_LONG).show();
                return true;
            case R.id.sub1_menu2:
                Toast.makeText(getApplicationContext(), "this is Sub menu1",
                        Toast.LENGTH_LONG).show();
                return true;
            case R.id.sub2_menu2:
                Toast.makeText(getApplicationContext(), "this is Sub menu2",
                        Toast.LENGTH_LONG).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


 

  4. Now run the application to test the Menus






No comments:

Post a Comment