Wednesday, November 23, 2011

Creating SubMenus in Android

In my previous post I expained how to create Context Menu. In this post I show how to create SubMenus in android.

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="SubMenu Example"
        android:textSize="20sp"
        android:gravity="center" />
       

</LinearLayout>

SubMenusActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.widget.Toast;

public class SubMenusActivity extends Activity {
   
    private static final int FILE=0;
    private static final int EDIT=1;
   
    private static final int NEW=Menu.FIRST;
    private static final int SAVE=NEW+1;
   
    private static final int UNDO=SAVE+1;
    private static final int REDO=UNDO+1;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        /*
         * To add a new sub menu to the menu
         */
        SubMenu file=menu.addSubMenu("File");
        SubMenu edit=menu.addSubMenu("Edit");
       
        file.setHeaderIcon(R.drawable.iconimage);
        /*
         * to add a new item to the menu
         */
        file.add(FILE,NEW,0,"New");
        file.add(FILE, SAVE, 1, "Save");
       
        edit.setHeaderIcon(R.drawable.iconimage);
        edit.add(EDIT,UNDO,0,"Undo");
        edit.add(EDIT,REDO,1,"Redo");
       
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())
        {
        case NEW:
            message("New");
            break;
        case SAVE:
            message("Save");
            break;
        case UNDO:
            message("Undo");
            break;
        case REDO:
            message("Redo");
        }
        return super.onOptionsItemSelected(item);
    }

    private void message(String msg) {
        msg+=" selected!!!";
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }
   
   
}

Before run this application put an image "iconimage" into the drawable folder.
Run your project and click on the menu button in emulator then you see the following output.



No comments:

Post a Comment