How to create OptionsMenu in ANDROID?, a simple example……

By | March 16, 2011

This is a simple example of creating options Menu in ANDROID.
This menu can be seen by clicking on the “Menu Button” in ANDROID.
Check out this example.

	package com.options;

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

	public class myMenu extends Activity {
	    @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);
	    }

	public boolean onCreateOptionsMenu(Menu menu) {
	  super.onCreateOptionsMenu(menu);
	  menu.add(0,0,0,"My Menu One");
	  menu.add(0,1,0,"My Menu two");
	  menu.add(0,2,0,"My Menu three");
	  menu.add(0,3,0,"My Menu Four");
	  menu.add(0,4,0,"My Menu Five");
	  return true;
	 }

	 public boolean onOptionsItemSelected(MenuItem item) {
	  super.onOptionsItemSelected(item);
	  TextView view = (TextView) findViewById(R.id.tv);
	  switch (item.getItemId()) {
	  case 0:
	      view.setText("Menu selected =>  "+item.getTitle());
	      break;
	  case 1:
		  view.setText("Menu selected => "+item.getTitle());
		  break;
	  case 2:
		  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 3:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 4:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 5:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  case 6:
	  	  view.setText("Menu selected => "+item.getTitle());
	  	  break;
	  default:
	          view.setText("Nothing found.");
	  break;
	  }
	  return false;
	 }

	 public boolean onPrepareOptionsMenu(Menu menu) {
	  return super.onPrepareOptionsMenu(menu);
	 }
	}

The main.xml for the above code is

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:id="@+id/tv"
    />
</LinearLayout>
Options Menu in ANDROID

Options Menu in ANDROID

Leave a Reply

Your email address will not be published. Required fields are marked *