Android Tutorial - UI Menu

Create Option menu

  

package app.Test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.LinearLayout;

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

  public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.mainmenu, menu);
    return true;
  }

  public boolean onOptionsItemSelected(MenuItem item) {
    LinearLayout bkgr = (LinearLayout) findViewById(R.id.uilayout);
    final ImageView image = (ImageView) findViewById(R.id.ImageView01);

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setTitle("Pick an Image!")
        .setMessage("Please Select Image One or Image Two:")
        .setCancelable(false)
        .setPositiveButton("IMAGE 1",
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                image.setImageResource(R.drawable.image1);
              }
            })

        .setNegativeButton("IMAGE 2",
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog, int id) {
                image.setImageResource(R.drawable.image2);
              }
            });

    switch (item.getItemId()) {
    case R.id.buttonone:
      image.setImageResource(R.drawable.image1);
      return true;
    case R.id.buttontwo:
      image.setImageResource(R.drawable.image2);
      return true;
    case R.id.buttonthree:
      bkgr.setBackgroundResource(R.color.background2);
      return true;
    case R.id.buttonfour:
      bkgr.setBackgroundResource(R.color.background);
      return true;
    case R.id.buttonfive:
      builder.show();
      return true;
    default:
      return super.onOptionsItemSelected(item);
    }
  }
}

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/uilayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/background">
    
  <ImageButton android:id="@+id/button_one"
          android:layout_width="wrap_content"
         android:layout_height="wrap_content"
          android:src="@drawable/button1"
          android:paddingTop="5px"
          android:background="#00000000">
  </ImageButton>
  
  <TextView  android:id="@+id/TextView01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Sample Text" 
        android:textColor="#CCCC77" 
        android:padding="12dip">
  </TextView>
  
  <ImageView  android:id="@+id/ImageView01" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:src="@drawable/image1">
  </ImageView>
  
</LinearLayout>


//mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>

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

    <item android:id="@+id/buttonone"
          android:icon="@drawable/image1icon"
          android:title="@string/showimage1" />
          
    <item android:id="@+id/buttontwo"
          android:icon="@drawable/image2icon"
          android:title="@string/showimage2" />
          
    <item android:id="@+id/buttonthree"
          android:icon="@drawable/menu3icon"
          android:title="@string/showwhite" />
          
    <item android:id="@+id/buttonfour"
          android:icon="@drawable/menu4icon"
          android:title="@string/showblack" />
          
    <item android:id="@+id/buttonfive"
          android:icon="@drawable/menu5icon"
          android:title="@string/showalert" />
          
</menu>

Menu and messages

package apt.tutorial;

import android.app.TabActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;

public class LunchList extends TabActivity {
  List<Restaurant> model=new ArrayList<Restaurant>();
  RestaurantAdapter adapter=null;
  EditText name=null;
  EditText address=null;
  EditText notes=null;
  RadioGroup types=null;
  Restaurant current=null;
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    
    name=(EditText)findViewById(R.id.name);
    address=(EditText)findViewById(R.id.addr);
    notes=(EditText)findViewById(R.id.notes);
    types=(RadioGroup)findViewById(R.id.types);
    
    Button save=(Button)findViewById(R.id.save);
    
    save.setOnClickListener(onSave);
    
    ListView list=(ListView)findViewById(R.id.restaurants);
    
    adapter=new RestaurantAdapter();
    list.setAdapter(adapter);
    
    TabHost.TabSpec spec=getTabHost().newTabSpec("tag1");
    
    spec.setContent(R.id.restaurants);
    spec.setIndicator("List", getResources()
                                .getDrawable(R.drawable.list));
    getTabHost().addTab(spec);
    
    spec=getTabHost().newTabSpec("tag2");
    spec.setContent(R.id.details);
    spec.setIndicator("Details", getResources()
                                  .getDrawable(R.drawable.restaurant));
    getTabHost().addTab(spec);
    
    getTabHost().setCurrentTab(0);
    
    list.setOnItemClickListener(onListClick);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.option, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.toast) {
      String message="No restaurant selected";
      
      if (current!=null) {
        message=current.getNotes();
      }
      
      Toast.makeText(this, message, Toast.LENGTH_LONG).show();
      
      return(true);
    }
    
    return(super.onOptionsItemSelected(item));
  }
  
  private View.OnClickListener onSave=new View.OnClickListener() {
    public void onClick(View v) {
      current=new Restaurant();
      current.setName(name.getText().toString());
      current.setAddress(address.getText().toString());
      current.setNotes(notes.getText().toString());
      
      switch (types.getCheckedRadioButtonId()) {
        case R.id.sit_down:
          current.setType("sit_down");
          break;
          
        case R.id.take_out:
          current.setType("take_out");
          break;
          
        case R.id.delivery:
          current.setType("delivery");
          break;
      }
      
      adapter.add(current);
    }
  };
  
  private AdapterView.OnItemClickListener onListClick=new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent,
                             View view, int position,
                             long id) {
      current=model.get(position);
      
      name.setText(current.getName());
      address.setText(current.getAddress());
      notes.setText(current.getNotes());
      
      if (current.getType().equals("sit_down")) {
        types.check(R.id.sit_down);
      }
      else if (current.getType().equals("take_out")) {
        types.check(R.id.take_out);
      }
      else {
        types.check(R.id.delivery);
      }
      
      getTabHost().setCurrentTab(1);
    }
  };
  
  class RestaurantAdapter extends ArrayAdapter<Restaurant> {
    RestaurantAdapter() {
      super(LunchList.this, R.layout.row, model);
    }
    
    public View getView(int position, View convertView,
                        ViewGroup parent) {
      View row=convertView;
      RestaurantHolder holder=null;
      
      if (row==null) {                          
        LayoutInflater inflater=getLayoutInflater();
        
        row=inflater.inflate(R.layout.row, parent, false);
        holder=new RestaurantHolder(row);
        row.setTag(holder);
      }
      else {
        holder=(RestaurantHolder)row.getTag();
      }
      
      holder.populateFrom(model.get(position));
      
      return(row);
    }
  }
  
  static class RestaurantHolder {
    private TextView name=null;
    private TextView address=null;
    private ImageView icon=null;
    
    RestaurantHolder(View row) {
      name=(TextView)row.findViewById(R.id.title);
      address=(TextView)row.findViewById(R.id.address);
      icon=(ImageView)row.findViewById(R.id.icon);
    }
    
    void populateFrom(Restaurant r) {
      name.setText(r.getName());
      address.setText(r.getAddress());
  
      if (r.getType().equals("sit_down")) {
        icon.setImageResource(R.drawable.ball_red);
      }
      else if (r.getType().equals("take_out")) {
        icon.setImageResource(R.drawable.ball_yellow);
      }
      else {
        icon.setImageResource(R.drawable.ball_green);
      }
    }
  }
}


package apt.tutorial;

public class Restaurant {
  private String name="";
  private String address="";
  private String type="";
  private String notes="";
  
  public String getName() {
    return(name);
  }
  
  public void setName(String name) {
    this.name=name;
  }
  
  public String getAddress() {
    return(address);
  }
  
  public void setAddress(String address) {
    this.address=address;
  }
  
  public String getType() {
    return(type);
  }
  
  public void setType(String type) {
    this.type=type;
  }
  
  public String getNotes() {
    return(notes);
  }
  
  public void setNotes(String notes) {
    this.notes=notes;
  }
  
  public String toString() {
    return(getName());
  }
}

//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">LunchList</string>
</resources>


//option.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/toast"
    android:title="Raise Toast"
    android:icon="@drawable/toast"
  />
</menu>

//main.xml

<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@android:id/tabhost"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TabWidget android:id="@android:id/tabs"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
    />
    <FrameLayout android:id="@android:id/tabcontent"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
    >
      <ListView android:id="@+id/restaurants"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
      />
      <TableLayout android:id="@+id/details"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:stretchColumns="1"
        android:paddingTop="4dip"
        >
        <TableRow>
          <TextView android:text="Name:" />
          <EditText android:id="@+id/name" />
        </TableRow>
        <TableRow>
          <TextView android:text="Address:" />
          <EditText android:id="@+id/addr" />
        </TableRow>
        <TableRow>
          <TextView android:text="Type:" />
          <RadioGroup android:id="@+id/types">
            <RadioButton android:id="@+id/take_out"
              android:text="Take-Out"
            />
            <RadioButton android:id="@+id/sit_down"
              android:text="Sit-Down"
            />
            <RadioButton android:id="@+id/delivery"
              android:text="Delivery"
            />
          </RadioGroup>
        </TableRow>
        <TableRow>
          <TextView android:text="Notes:" />
          <EditText android:id="@+id/notes"
            android:singleLine="false"
            android:gravity="top"
            android:lines="2"
            android:scrollHorizontally="false"
            android:maxLines="2"
            android:maxWidth="200sp"
          />
        </TableRow>
        <Button android:id="@+id/save"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="Save"
        />
      </TableLayout>
    </FrameLayout>
  </LinearLayout>
</TabHost>

//row.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:orientation="horizontal"
  android:padding="4dip"
  >
  <ImageView android:id="@+id/icon"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="4dip"
  />
  <LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >  
    <TextView android:id="@+id/title"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:textStyle="bold"
      android:singleLine="true"
      android:ellipsize="end"
    />
    <TextView android:id="@+id/address"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center_vertical"
      android:singleLine="true"
      android:ellipsize="end"
    />
  </LinearLayout>
</LinearLayout>

Context menu

  

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class Test extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //Register a button for context events
        Button button = new Button(this);
        button.setText("Click for Options");
        button.setOnClickListener(listener);
        registerForContextMenu(button);

        setContentView(button);
    }

    View.OnClickListener listener = new View.OnClickListener() {
        public void onClick(View v) {
            openContextMenu(v);
        }
    };

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
                ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        getMenuInflater().inflate(R.menu.contextmenu, menu);
        menu.setHeaderTitle("Choose an Option");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        //Switch on the item? ID to find the action the user selected
        switch(item.getItemId()) {
        case R.id.menu_delete:
            //Perform delete actions
            return true;
        case R.id.menu_copy:
            //Perform copy actions
            return true;
        case R.id.menu_edit:
            //Perform edit actions
            return true;
        }
        return super.onContextItemSelected(item);
    }

}

//contextmenu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:id="@+id/menu_delete"
    android:title="Delete Item"
  />
  <item
    android:id="@+id/menu_copy"
    android:title="Copy Item"
  />
  <item
    android:id="@+id/menu_edit"
    android:title="Edit Item"
  />
</menu>

Custom menu

  

package com.examples.keys;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.view.KeyEvent;
import android.view.View;

public class MyActivity extends Activity {

    MenuDialog menuDialog;
    private class MenuDialog extends AlertDialog {

        public MenuDialog(Context context) {
            super(context);
            View menu = getLayoutInflater().inflate(R.layout.custommenu, null);
            setView(menu);
        }

        @Override
        public boolean onKeyUp(int keyCode, KeyEvent event) {
            if(keyCode == KeyEvent.KEYCODE_MENU) {
                dismiss();
                return true;
            }
            return super.onKeyUp(keyCode, event);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_MENU) {
            if(menuDialog == null) {
                menuDialog = new MenuDialog(this);
            }
            menuDialog.show();
            return true;
        }

        return super.onKeyUp(keyCode, event);
    }

}
//custommenu.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="wrap_content"
  android:orientation="horizontal">
  <ImageButton android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_weight="1"
    android:src="@android:drawable/ic_menu_send" />
  <ImageButton android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_weight="1"
    android:src="@android:drawable/ic_menu_save" />
  <ImageButton android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_weight="1"
    android:src="@android:drawable/ic_menu_search" />
  <ImageButton android:layout_width="fill_parent"
    android:layout_height="wrap_content" android:layout_weight="1"
    android:src="@android:drawable/ic_menu_preferences" />
</LinearLayout>

Using Icon in Menu

package app.test;

import java.util.HashMap;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;

class Provider extends ContentProvider {
  private static final String DATABASE_NAME = "constants.db";
  private static final int CONSTANTS = 1;
  private static final int CONSTANT_ID = 2;
  private static final UriMatcher MATCHER;
  private static HashMap<String, String> CONSTANTS_LIST_PROJECTION;

  public static final class Constants implements BaseColumns {
    public static final Uri CONTENT_URI = Uri
        .parse("content://com.commonsware.android.constants.Provider/constants");
    public static final String DEFAULT_SORT_ORDER = "title";
    public static final String TITLE = "title";
    public static final String VALUE = "value";
  }

  static {
    MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
    MATCHER.addURI("com.commonsware.android.constants.Provider",
        "constants", CONSTANTS);
    MATCHER.addURI("com.commonsware.android.constants.Provider",
        "constants/#", CONSTANT_ID);

    CONSTANTS_LIST_PROJECTION = new HashMap<String, String>();
    CONSTANTS_LIST_PROJECTION.put(Provider.Constants._ID,
        Provider.Constants._ID);
    CONSTANTS_LIST_PROJECTION.put(Provider.Constants.TITLE,
        Provider.Constants.TITLE);
    CONSTANTS_LIST_PROJECTION.put(Provider.Constants.VALUE,
        Provider.Constants.VALUE);
  }

  public String getDbName() {
    return (DATABASE_NAME);
  }

  public int getDbVersion() {
    return (1);
  }

  private class DatabaseHelper extends SQLiteOpenHelper {
    public DatabaseHelper(Context context) {
      super(context, DATABASE_NAME, null, 1);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
      Cursor c = db
          .rawQuery(
              "SELECT name FROM sqlite_master WHERE type='table' AND name='constants'",
              null);

      try {
        if (c.getCount() == 0) {
          db.execSQL("CREATE TABLE constants (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, value REAL);");

          ContentValues cv = new ContentValues();

          cv.put(Constants.TITLE, "Gravity, Death Star I");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_DEATH_STAR_I);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Earth");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_EARTH);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Jupiter");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_JUPITER);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Mars");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_MARS);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Mercury");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_MERCURY);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Moon");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_MOON);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Neptune");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_NEPTUNE);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Pluto");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_PLUTO);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Saturn");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_SATURN);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Sun");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_SUN);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, The Island");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_THE_ISLAND);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Uranus");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_URANUS);
          db.insert("constants", getNullColumnHack(), cv);

          cv.put(Constants.TITLE, "Gravity, Venus");
          cv.put(Constants.VALUE, SensorManager.GRAVITY_VENUS);
          db.insert("constants", getNullColumnHack(), cv);
        }
      } finally {
        c.close();
      }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
      android.util.Log.w("Constants",
          "Upgrading database, which will destroy all old data");
      db.execSQL("DROP TABLE IF EXISTS constants");
      onCreate(db);
    }
  }

  private SQLiteDatabase db;

  @Override
  public boolean onCreate() {
    db = (new DatabaseHelper(getContext())).getWritableDatabase();

    return (db == null) ? false : true;
  }

  @Override
  public Cursor query(Uri url, String[] projection, String selection,
      String[] selectionArgs, String sort) {
    SQLiteQueryBuilder qb = new SQLiteQueryBuilder();

    qb.setTables(getTableName());

    if (isCollectionUri(url)) {
      qb.setProjectionMap(getDefaultProjection());
    } else {
      qb.appendWhere(getIdColumnName() + "="
          + url.getPathSegments().get(1));
    }

    String orderBy;

    if (TextUtils.isEmpty(sort)) {
      orderBy = getDefaultSortOrder();
    } else {
      orderBy = sort;
    }

    Cursor c = qb.query(db, projection, selection, selectionArgs, null,
        null, orderBy);
    c.setNotificationUri(getContext().getContentResolver(), url);
    return c;
  }

  @Override
  public String getType(Uri url) {
    if (isCollectionUri(url)) {
      return (getCollectionType());
    }

    return (getSingleType());
  }

  @Override
  public Uri insert(Uri url, ContentValues initialValues) {
    long rowID;
    ContentValues values;

    if (initialValues != null) {
      values = new ContentValues(initialValues);
    } else {
      values = new ContentValues();
    }

    if (!isCollectionUri(url)) {
      throw new IllegalArgumentException("Unknown URL " + url);
    }

    for (String colName : getRequiredColumns()) {
      if (values.containsKey(colName) == false) {
        throw new IllegalArgumentException("Missing column: " + colName);
      }
    }

    populateDefaultValues(values);

    rowID = db.insert(getTableName(), getNullColumnHack(), values);
    if (rowID > 0) {
      Uri uri = ContentUris.withAppendedId(getContentUri(), rowID);
      getContext().getContentResolver().notifyChange(uri, null);
      return uri;
    }

    throw new SQLException("Failed to insert row into " + url);
  }

  @Override
  public int delete(Uri url, String where, String[] whereArgs) {
    int count;
    long rowId = 0;

    if (isCollectionUri(url)) {
      count = db.delete(getTableName(), where, whereArgs);
    } else {
      String segment = url.getPathSegments().get(1);
      rowId = Long.parseLong(segment);
      count = db.delete(
          getTableName(),
          getIdColumnName()
              + "="
              + segment
              + (!TextUtils.isEmpty(where) ? " AND (" + where
                  + ')' : ""), whereArgs);
    }

    getContext().getContentResolver().notifyChange(url, null);
    return count;
  }

  @Override
  public int update(Uri url, ContentValues values, String where,
      String[] whereArgs) {
    int count;

    if (isCollectionUri(url)) {
      count = db.update(getTableName(), values, where, whereArgs);
    } else {
      String segment = url.getPathSegments().get(1);
      count = db.update(
          getTableName(),
          values,
          getIdColumnName()
              + "="
              + segment
              + (!TextUtils.isEmpty(where) ? " AND (" + where
                  + ')' : ""), whereArgs);
    }

    getContext().getContentResolver().notifyChange(url, null);
    return count;
  }

  private boolean isCollectionUri(Uri url) {
    return (MATCHER.match(url) == CONSTANTS);
  }

  private HashMap<String, String> getDefaultProjection() {
    return (CONSTANTS_LIST_PROJECTION);
  }

  private String getTableName() {
    return ("constants");
  }

  private String getIdColumnName() {
    return ("_id");
  }

  private String getDefaultSortOrder() {
    return ("title");
  }

  private String getCollectionType() {
    return ("vnd.android.cursor.dir/vnd.commonsware.constant");
  }

  private String getSingleType() {
    return ("vnd.android.cursor.item/vnd.commonsware.constant");
  }

  private String[] getRequiredColumns() {
    return (new String[] { "title" });
  }

  private void populateDefaultValues(ContentValues values) {
    Long now = Long.valueOf(System.currentTimeMillis());
    Resources r = Resources.getSystem();

    if (values.containsKey(Provider.Constants.VALUE) == false) {
      values.put(Provider.Constants.VALUE, 0.0f);
    }
  }

  private String getNullColumnHack() {
    return ("title");
  }

  private Uri getContentUri() {
    return (Provider.Constants.CONTENT_URI);
  }
}

public class Test extends ListActivity {
  private static final int ADD_ID = Menu.FIRST + 1;
  private static final int EDIT_ID = Menu.FIRST + 2;
  private static final int DELETE_ID = Menu.FIRST + 3;
  private static final int CLOSE_ID = Menu.FIRST + 4;
  private static final String[] PROJECTION = new String[] {
      Provider.Constants._ID, Provider.Constants.TITLE,
      Provider.Constants.VALUE };
  private Cursor constantsCursor;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    constantsCursor = managedQuery(Provider.Constants.CONTENT_URI,
        PROJECTION, null, null, null);

    ListAdapter adapter = new SimpleCursorAdapter(this, R.layout.row,
        constantsCursor, new String[] { Provider.Constants.TITLE,
            Provider.Constants.VALUE }, new int[] { R.id.title,
            R.id.value });

    setListAdapter(adapter);
    registerForContextMenu(getListView());
  }

  @Override
  public void onDestroy() {
    super.onDestroy();

    constantsCursor.close();
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    menu.add(Menu.NONE, ADD_ID, Menu.NONE, "Add").setIcon(R.drawable.icon)
        .setAlphabeticShortcut('a');
    menu.add(Menu.NONE, CLOSE_ID, Menu.NONE, "Close")
        .setIcon(R.drawable.icon).setAlphabeticShortcut('c');

    return (super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case ADD_ID:
      add();
      return (true);

    case CLOSE_ID:
      finish();
      return (true);
    }

    return (super.onOptionsItemSelected(item));
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenu.ContextMenuInfo menuInfo) {
    menu.add(Menu.NONE, DELETE_ID, Menu.NONE, "Delete")
        .setIcon(R.drawable.icon).setAlphabeticShortcut('d');
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case DELETE_ID:
      AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item
          .getMenuInfo();

      delete(info.id);
      return (true);
    }

    return (super.onOptionsItemSelected(item));
  }

  private void add() {
    LayoutInflater inflater = LayoutInflater.from(this);
    View addView = inflater.inflate(R.layout.add_edit, null);
    final DialogWrapper wrapper = new DialogWrapper(addView);

    new AlertDialog.Builder(this)
        .setTitle(R.string.add_title)
        .setView(addView)
        .setPositiveButton(R.string.ok,
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                  int whichButton) {
                processAdd(wrapper);
              }
            })
        .setNegativeButton(R.string.cancel,
            new DialogInterface.OnClickListener() {
              public void onClick(DialogInterface dialog,
                  int whichButton) {
                // ignore, just dismiss
              }
            }).show();
  }

  private void delete(final long rowId) {
    if (rowId > 0) {
      new AlertDialog.Builder(this)
          .setTitle(R.string.delete_title)
          .setPositiveButton(R.string.ok,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                    int whichButton) {
                  processDelete(rowId);
                }
              })
          .setNegativeButton(R.string.cancel,
              new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,
                    int whichButton) {
                  // ignore, just dismiss
                }
              }).show();
    }
  }

  private void processAdd(DialogWrapper wrapper) {
    ContentValues values = new ContentValues(2);

    values.put(Provider.Constants.TITLE, wrapper.getTitle());
    values.put(Provider.Constants.VALUE, wrapper.getValue());

    getContentResolver().insert(Provider.Constants.CONTENT_URI, values);
    constantsCursor.requery();
  }

  private void processDelete(long rowId) {
    Uri uri = ContentUris.withAppendedId(Provider.Constants.CONTENT_URI,
        rowId);
    getContentResolver().delete(uri, null, null);
    constantsCursor.requery();
  }

  class DialogWrapper {
    EditText titleField = null;
    EditText valueField = null;
    View base = null;

    DialogWrapper(View base) {
      this.base = base;
      valueField = (EditText) base.findViewById(R.id.value);
    }

    String getTitle() {
      return (getTitleField().getText().toString());
    }

    float getValue() {
      return (new Float(getValueField().getText().toString())
          .floatValue());
    }

    private EditText getTitleField() {
      if (titleField == null) {
        titleField = (EditText) base.findViewById(R.id.title);
      }

      return (titleField);
    }

    private EditText getValueField() {
      if (valueField == null) {
        valueField = (EditText) base.findViewById(R.id.value);
      }

      return (valueField);
    }
  }
}

//main.xml

<?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="Hello World, ConstantsBrowser"
    />
</LinearLayout>

//add_edit.xml

<?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="wrap_content"
    >
  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      >
    <TextView
        android:text="Display Name:"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        />
    <EditText
        android:id="@+id/title"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true"
        />
  </LinearLayout>
  <LinearLayout
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      >
    <TextView
        android:text="Value:"
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        />
    <EditText
        android:id="@+id/value"
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:layout_alignParentRight="true"
        />
  </LinearLayout>
</LinearLayout>

//row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
  <TextView
      android:id="@+id/title"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      />
  <TextView
      android:id="@+id/value"
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentRight="true"
      />
</RelativeLayout>

//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">ConstantsBrowser</string>
    <string name="ok">OK</string>
    <string name="cancel">Cancel</string>
    <string name="add_title">Add Constant</string>
    <string name="delete_title">Delete Constant: Are You Sure?</string>
</resources>
Option Menu selection event
package com.commonsware.android.inflation;

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;

public class InflationDemo extends Activity {
  private final static Map<Integer,String> MESSAGES;
  private boolean otherStuffVisible=false;
  private Menu theMenu=null;
  
  static {
    MESSAGES=new HashMap<Integer,String>();
    MESSAGES.put(R.id.close, "I don't wanna!");
    MESSAGES.put(R.id.no_icon, "Where's my picture?");
    MESSAGES.put(R.id.later, "Quoth the Maven, \"#4\"");
    MESSAGES.put(R.id.last, "i always get picked last...");
    MESSAGES.put(R.id.non_ghost, "I ain't 'fraid of no ghost!");
    MESSAGES.put(R.id.ghost, "Boo!");
  };
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    theMenu=menu;
    
    new MenuInflater(getApplication())
                                  .inflate(R.menu.sample, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.non_ghost) {
      otherStuffVisible=!otherStuffVisible;
      
      theMenu.setGroupVisible(R.id.other_stuff, otherStuffVisible);
    }
    
    String message=MESSAGES.get(item.getItemId());
    
    if (message!=null) {
      Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
      
      return(true);
    }
    
    return(super.onOptionsItemSelected(item));
  }
}

//res\layout\main.xml
<?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="Click on the option menu and play with the choices!"
    />
</LinearLayout>



//res\menu\sample.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/close"
    android:title="Close"
    android:orderInCategory="3"
    android:icon="@drawable/eject" />
  <item android:id="@+id/no_icon"
    android:orderInCategory="2"
    android:title="Sans Icon" />
  <item android:id="@+id/disabled"
    android:orderInCategory="4"
    android:enabled="false"
    android:title="Disabled" />
  <group android:id="@+id/other_stuff"
    android:menuCategory="secondary"
    android:visible="false">
    <item android:id="@+id/later"
      android:orderInCategory="0"
      android:title="2nd-To-Last" />
    <item android:id="@+id/last"
      android:orderInCategory="1"
      android:title="Last" />
  </group>
  <item android:id="@+id/submenu"
    android:orderInCategory="3"
    android:title="A Submenu">
    <menu>        
      <item android:id="@+id/non_ghost"
        android:title="Non-Ghost"
        android:visible="true"
        android:alphabeticShortcut="n" />
      <item android:id="@+id/ghost"
        android:title="A Ghost"
        android:visible="false"
        android:alphabeticShortcut="g" />
    </menu>
  </item>
</menu>

Menu Inflation

package com.commonsware.android.inflation;

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;

public class InflationDemo extends Activity {
  private final static Map<Integer,String> MESSAGES;
  private boolean otherStuffVisible=false;
  private Menu theMenu=null;
  
  static {
    MESSAGES=new HashMap<Integer,String>();
    MESSAGES.put(R.id.close, "I don't wanna!");
    MESSAGES.put(R.id.no_icon, "Where's my picture?");
    MESSAGES.put(R.id.later, "Quoth the Maven, \"#4\"");
    MESSAGES.put(R.id.last, "i always get picked last...");
    MESSAGES.put(R.id.non_ghost, "I ain't 'fraid of no ghost!");
    MESSAGES.put(R.id.ghost, "Boo!");
  };
  
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    theMenu=menu;
    
    new MenuInflater(getApplication())
                                  .inflate(R.menu.sample, menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.non_ghost) {
      otherStuffVisible=!otherStuffVisible;
      
      theMenu.setGroupVisible(R.id.other_stuff, otherStuffVisible);
    }
    
    String message=MESSAGES.get(item.getItemId());
    
    if (message!=null) {
      Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
      
      return(true);
    }
    
    return(super.onOptionsItemSelected(item));
  }
}

//res\layout\main.xml
<?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="Click on the option menu and play with the choices!"
    />
</LinearLayout>



//res\menu\sample.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:id="@+id/close"
    android:title="Close"
    android:orderInCategory="3"
    android:icon="@drawable/eject" />
  <item android:id="@+id/no_icon"
    android:orderInCategory="2"
    android:title="Sans Icon" />
  <item android:id="@+id/disabled"
    android:orderInCategory="4"
    android:enabled="false"
    android:title="Disabled" />
  <group android:id="@+id/other_stuff"
    android:menuCategory="secondary"
    android:visible="false">
    <item android:id="@+id/later"
      android:orderInCategory="0"
      android:title="2nd-To-Last" />
    <item android:id="@+id/last"
      android:orderInCategory="1"
      android:title="Last" />
  </group>
  <item android:id="@+id/submenu"
    android:orderInCategory="3"
    android:title="A Submenu">
    <menu>        
      <item android:id="@+id/non_ghost"
        android:title="Non-Ghost"
        android:visible="true"
        android:alphabeticShortcut="n" />
      <item android:id="@+id/ghost"
        android:title="A Ghost"
        android:visible="false"
        android:alphabeticShortcut="g" />
    </menu>
  </item>
</menu>
Context Menu event
package com.commonsware.android.menus;

import android.app.Activity;
import android.os.Bundle;
import android.app.ListActivity;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;


public class MenuDemo extends ListActivity {
  TextView selection;
  String[] items={"lorem", "ipsum", "dolor", "sit", "amet",
          "consectetuer", "adipiscing", "elit", "morbi", "vel",
          "ligula", "vitae", "arcu", "aliquet", "mollis",
          "etiam", "vel", "erat", "placerat", "ante",
          "porttitor", "sodales", "pellentesque", "augue", "purus"};
  public static final int EIGHT_ID = Menu.FIRST+1;
  public static final int SIXTEEN_ID = Menu.FIRST+2;
  public static final int TWENTY_FOUR_ID = Menu.FIRST+3;
  public static final int TWO_ID = Menu.FIRST+4;
  public static final int THIRTY_TWO_ID = Menu.FIRST+5;
  public static final int FORTY_ID = Menu.FIRST+6;
  public static final int ONE_ID = Menu.FIRST+7;

  @Override
  public void onCreate(Bundle icicle) {
    super.onCreate(icicle);
    setContentView(R.layout.main);
    setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, items));
    selection=(TextView)findViewById(R.id.selection);
    
    registerForContextMenu(getListView());
  }
  
  public void onListItemClick(ListView parent, View v,
                                int position, long id) {
     selection.setText(items[position]);
  }
  
  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
                                    ContextMenu.ContextMenuInfo menuInfo) {
    populateMenu(menu);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    populateMenu(menu);

    return(super.onCreateOptionsMenu(menu));
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    return(applyMenuChoice(item) ||
            super.onOptionsItemSelected(item));
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    return(applyMenuChoice(item) ||
            super.onContextItemSelected(item));
  }
  
  private void populateMenu(Menu menu) {
    menu.add(Menu.NONE, ONE_ID, Menu.NONE, "1 Pixel");
    menu.add(Menu.NONE, TWO_ID, Menu.NONE, "2 Pixels");
    menu.add(Menu.NONE, EIGHT_ID, Menu.NONE, "8 Pixels");
    menu.add(Menu.NONE, SIXTEEN_ID, Menu.NONE, "16 Pixels");
    menu.add(Menu.NONE, TWENTY_FOUR_ID, Menu.NONE, "24 Pixels");
    menu.add(Menu.NONE, THIRTY_TWO_ID, Menu.NONE, "32 Pixels");
    menu.add(Menu.NONE, FORTY_ID, Menu.NONE, "40 Pixels");
  }
  
  private boolean applyMenuChoice(MenuItem item) {
    switch (item.getItemId()) {
      case ONE_ID:
        getListView().setDividerHeight(1);
        return(true);
    
      case EIGHT_ID:
        getListView().setDividerHeight(8);
        return(true);
    
      case SIXTEEN_ID:
        getListView().setDividerHeight(16);
        return(true);
    
      case TWENTY_FOUR_ID:
        getListView().setDividerHeight(24);
        return(true);
    
      case TWO_ID:
        getListView().setDividerHeight(2);
        return(true);
    
      case THIRTY_TWO_ID:
        getListView().setDividerHeight(32);
        return(true);
    
      case FORTY_ID:
        getListView().setDividerHeight(40);
        return(true);
    }

    return(false);
  }
}



//res\layout\main.xml
<?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:id="@+id/selection"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#eeeeee"/>
  <ListView
    android:id="@android:id/list"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"
    android:drawSelectorOnTop="false"
    />
</LinearLayout>

Create Menu within your code

  

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

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

    Button btn = (Button) findViewById(R.id.btn1);
    btn.setOnCreateContextMenuListener(this);
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    CreateMenu(menu);
    return true;
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    return MenuChoice(item);
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View view,
      ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, view, menuInfo);
    CreateMenu(menu);
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    return MenuChoice(item);
  }

  private void CreateMenu(Menu menu) {
    menu.setQwertyMode(true);
    MenuItem mnu1 = menu.add(0, 0, 0, "Item 1");
    {
      mnu1.setAlphabeticShortcut('a');
      mnu1.setIcon(R.drawable.icon);
    }
    MenuItem mnu2 = menu.add(0, 1, 1, "Item 2");
    {
      mnu2.setAlphabeticShortcut('b');
      mnu2.setIcon(R.drawable.icon);
    }
    MenuItem mnu3 = menu.add(0, 2, 2, "Item 3");
    {
      mnu3.setAlphabeticShortcut('c');
      mnu3.setIcon(R.drawable.icon);
    }
    MenuItem mnu4 = menu.add(0, 3, 3, "Item 4");
    {
      mnu4.setAlphabeticShortcut('d');
    }
    menu.add(0, 3, 3, "Item 5");
    menu.add(0, 3, 3, "Item 6");
    menu.add(0, 3, 3, "Item 7");
  }

  private boolean MenuChoice(MenuItem item) {
    switch (item.getItemId()) {
    case 0:
      Toast.makeText(this, "You clicked on Item 1", Toast.LENGTH_LONG)
          .show();
      return true;
    case 1:
      Toast.makeText(this, "You clicked on Item 2", Toast.LENGTH_LONG)
          .show();
      return true;
    case 2:
      Toast.makeText(this, "You clicked on Item 3", Toast.LENGTH_LONG)
          .show();
      return true;
    case 3:
      Toast.makeText(this, "You clicked on Item 4", Toast.LENGTH_LONG)
          .show();
      return true;
    case 4:
      Toast.makeText(this, "You clicked on Item 5", Toast.LENGTH_LONG)
          .show();
      return true;
    case 5:
      Toast.makeText(this, "You clicked on Item 6", Toast.LENGTH_LONG)
          .show();
      return true;
    case 6:
      Toast.makeText(this, "You clicked on Item 7", Toast.LENGTH_LONG)
          .show();
      return true;
    }
    return false;
  }
}
//main.xml

<?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"
    >
<Button android:id="@+id/btn1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:text = "Tap and hold this for more options..." />     

</LinearLayout>
Activity Menu
package app.test;

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


public class Test extends Activity {
  public static final int ITEM0 = Menu.FIRST;
  public static final int ITEM1 = Menu.FIRST + 1;

  Button button1;
  Button button2;
  
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        button1 = (Button) findViewById(R.id.button1);
    button2 = (Button) findViewById(R.id.button2);
    button1.setVisibility(View.INVISIBLE);
    button2.setVisibility(View.INVISIBLE);
    

    }
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    menu.add(0, ITEM0, 0, "button1");
    menu.add(0, ITEM1, 0, "button2");
    menu.findItem(ITEM1);
    return true;
  }
  
  public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case ITEM0: 
      actionClickMenuItem1();
    break;
    case ITEM1: 
      actionClickMenuItem2(); break;

    }
    return super.onOptionsItemSelected(item);}
  private void actionClickMenuItem1(){
    setTitle("button1");
    button1.setVisibility(View.VISIBLE);
    button2.setVisibility(View.INVISIBLE);
  }

  private void actionClickMenuItem2(){
    setTitle("button2");
    button1.setVisibility(View.INVISIBLE);
    button2.setVisibility(View.VISIBLE);
  }
}

//main.xml
<?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" />
  <Button android:id="@+id/button1"
    android:layout_width="100px"
    android:layout_height="wrap_content" android:text="@string/button1" />
  <Button android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" android:text="@string/button2" />
</LinearLayout>


//strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string name="hello">Hello World, ActivityMenu</string>
  <string name="app_name">HelloMenu</string>
  <string name="button1">button1</string>
  <string name="button2">button2</string>
</resources>

Define menu in xml file

  

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.TextView;

public class Test extends Activity {
  Menu myMenu = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    registerForContextMenu(this.getTextView());
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    this.myMenu = menu;
    addRegularMenuItems(menu);
    add5SecondaryMenuItems(menu);
    this.addSubMenu(menu);
    return true;
  }

  private void addRegularMenuItems(Menu menu) {
    int base = Menu.FIRST; // value is 1

    MenuItem item1 = menu.add(base, base, base, "append");
    menu.add(base, base + 1, base + 1, "item 2");
    menu.add(base, base + 2, base + 2, "clear");

    menu.add(base, base + 3, base + 3, "hide secondary");
    menu.add(base, base + 4, base + 4, "show secondary");

    menu.add(base, base + 5, base + 5, "enable secondary");
    menu.add(base, base + 6, base + 6, "disable secondary");

    menu.add(base, base + 7, base + 7, "check secondary");
    MenuItem item8 = menu
        .add(base, base + 8, base + 8, "uncheck secondary");
    item1.setIcon(R.drawable.icon);
    item8.setIcon(R.drawable.icon);
  }

  private void add5SecondaryMenuItems(Menu menu) {
    int base = Menu.CATEGORY_SECONDARY;

    menu.add(base, base + 1, base + 1, "sec. item 1");
    menu.add(base, base + 2, base + 2, "sec. item 2");
    menu.add(base, base + 3, base + 3, "sec. item 3");
    menu.add(base, base + 3, base + 3, "sec. item 4");
    menu.add(base, base + 4, base + 4, "sec. item 5");
  }

  private void addSubMenu(Menu menu) {
    int base = Menu.FIRST + 100;
    SubMenu sm = menu.addSubMenu(base, base + 1, Menu.NONE, "submenu");
    MenuItem item1 = sm.add(base, base + 2, base + 2, "sub item1");

    sm.add(base, base + 3, base + 3, "sub item2");
    sm.add(base, base + 4, base + 4, "sub item3");
    item1.setIcon(R.drawable.icon);
    sm.setIcon(R.drawable.icon);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == 1) {
      appendText("\nhello");
    } else if (item.getItemId() == 2) {
      appendText("\nitem2");
    } else if (item.getItemId() == 3) {
      emptyText();
    } else if (item.getItemId() == 4) {
      // hide secondary
      this.appendMenuItemText(item);
      this.myMenu.setGroupVisible(Menu.CATEGORY_SECONDARY, false);
    } else if (item.getItemId() == 5) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupVisible(Menu.CATEGORY_SECONDARY, true);
    } else if (item.getItemId() == 6) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupEnabled(Menu.CATEGORY_SECONDARY, true);
    } else if (item.getItemId() == 7) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupEnabled(Menu.CATEGORY_SECONDARY, false);
    } else if (item.getItemId() == 8) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupCheckable(Menu.CATEGORY_SECONDARY, true, false);
    } else if (item.getItemId() == 9) {
      this.appendMenuItemText(item);
      this.myMenu
          .setGroupCheckable(Menu.CATEGORY_SECONDARY, false, false);
    } else {
      this.appendMenuItemText(item);
    }
    return true;
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("Sample menu");
    menu.add(200, 200, 200, "item1");
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    this.appendMenuItemText(item);
    return true;
  }

  private void loadXMLMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater(); // from activity
    inflater.inflate(R.menu.my_menu, menu);
  }

  private TextView getTextView() {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    return tv;
  }

  public void appendText(String text) {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText(tv.getText() + text);
  }

  private void appendMenuItemText(MenuItem menuItem) {
    String title = menuItem.getTitle().toString();
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText(tv.getText() + "\n" + title + ":" + menuItem.getItemId());
  }

  private void emptyText() {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText("");
  }
}

//main.xml
<?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:id="@+id/textViewId"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
</LinearLayout>

//menu/my_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This group uses the default category. -->
    <group android:id="@+id/menuGroup_Main">

        <item android:id="@+id/menu_testPick"
            android:orderInCategory="5"
            android:title="Test Pick" />
            
        <item android:id="@+id/menu_testGetContent"
            android:orderInCategory="5"
            android:title="Test Get Content" />
            
        <item android:id="@+id/menu_clear"
            android:orderInCategory="10"
            android:title="clear" />
            
        <item android:id="@+id/menu_dial"
            android:orderInCategory="7"
            android:title="dial" />
            
        <item android:id="@+id/menu_test"
            android:orderInCategory="4"
            android:title="@+string/test" />
            
        <item android:id="@+id/menu_show_browser"
            android:orderInCategory="5"
            android:title="show browser" />
    </group>
</menu>
Adding submenu
package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.TextView;

public class Test extends Activity {
  Menu myMenu = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    registerForContextMenu(this.getTextView());
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    this.myMenu = menu;
    addRegularMenuItems(menu);
    add5SecondaryMenuItems(menu);
    this.addSubMenu(menu);
    return true;
  }

  private void addRegularMenuItems(Menu menu) {
    int base = Menu.FIRST; // value is 1

    MenuItem item1 = menu.add(base, base, base, "append");
    menu.add(base, base + 1, base + 1, "item 2");
    menu.add(base, base + 2, base + 2, "clear");

    menu.add(base, base + 3, base + 3, "hide secondary");
    menu.add(base, base + 4, base + 4, "show secondary");

    menu.add(base, base + 5, base + 5, "enable secondary");
    menu.add(base, base + 6, base + 6, "disable secondary");

    menu.add(base, base + 7, base + 7, "check secondary");
    MenuItem item8 = menu
        .add(base, base + 8, base + 8, "uncheck secondary");
    item1.setIcon(R.drawable.icon);
    item8.setIcon(R.drawable.icon);
  }

  private void add5SecondaryMenuItems(Menu menu) {
    int base = Menu.CATEGORY_SECONDARY;

    menu.add(base, base + 1, base + 1, "sec. item 1");
    menu.add(base, base + 2, base + 2, "sec. item 2");
    menu.add(base, base + 3, base + 3, "sec. item 3");
    menu.add(base, base + 3, base + 3, "sec. item 4");
    menu.add(base, base + 4, base + 4, "sec. item 5");
  }

  private void addSubMenu(Menu menu) {
    int base = Menu.FIRST + 100;
    SubMenu sm = menu.addSubMenu(base, base + 1, Menu.NONE, "submenu");
    MenuItem item1 = sm.add(base, base + 2, base + 2, "sub item1");

    sm.add(base, base + 3, base + 3, "sub item2");
    sm.add(base, base + 4, base + 4, "sub item3");
    item1.setIcon(R.drawable.icon);
    sm.setIcon(R.drawable.icon);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == 1) {
      appendText("\nhello");
    } else if (item.getItemId() == 2) {
      appendText("\nitem2");
    } else if (item.getItemId() == 3) {
      emptyText();
    } else if (item.getItemId() == 4) {
      // hide secondary
      this.appendMenuItemText(item);
      this.myMenu.setGroupVisible(Menu.CATEGORY_SECONDARY, false);
    } else if (item.getItemId() == 5) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupVisible(Menu.CATEGORY_SECONDARY, true);
    } else if (item.getItemId() == 6) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupEnabled(Menu.CATEGORY_SECONDARY, true);
    } else if (item.getItemId() == 7) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupEnabled(Menu.CATEGORY_SECONDARY, false);
    } else if (item.getItemId() == 8) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupCheckable(Menu.CATEGORY_SECONDARY, true, false);
    } else if (item.getItemId() == 9) {
      this.appendMenuItemText(item);
      this.myMenu
          .setGroupCheckable(Menu.CATEGORY_SECONDARY, false, false);
    } else {
      this.appendMenuItemText(item);
    }
    return true;
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("Sample menu");
    menu.add(200, 200, 200, "item1");
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    this.appendMenuItemText(item);
    return true;
  }

  private void loadXMLMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater(); // from activity
    inflater.inflate(R.menu.my_menu, menu);
  }

  private TextView getTextView() {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    return tv;
  }

  public void appendText(String text) {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText(tv.getText() + text);
  }

  private void appendMenuItemText(MenuItem menuItem) {
    String title = menuItem.getTitle().toString();
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText(tv.getText() + "\n" + title + ":" + menuItem.getItemId());
  }

  private void emptyText() {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText("");
  }
}

//main.xml
<?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:id="@+id/textViewId"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
</LinearLayout>

//menu/my_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This group uses the default category. -->
    <group android:id="@+id/menuGroup_Main">

        <item android:id="@+id/menu_testPick"
            android:orderInCategory="5"
            android:title="Test Pick" />
            
        <item android:id="@+id/menu_testGetContent"
            android:orderInCategory="5"
            android:title="Test Get Content" />
            
        <item android:id="@+id/menu_clear"
            android:orderInCategory="10"
            android:title="clear" />
            
        <item android:id="@+id/menu_dial"
            android:orderInCategory="7"
            android:title="dial" />
            
        <item android:id="@+id/menu_test"
            android:orderInCategory="4"
            android:title="@+string/test" />
            
        <item android:id="@+id/menu_show_browser"
            android:orderInCategory="5"
            android:title="show browser" />
    </group>
</menu>

Using Icon in menu and submenu

package app.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.TextView;

public class Test extends Activity {
  Menu myMenu = null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    registerForContextMenu(this.getTextView());
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    this.myMenu = menu;
    addRegularMenuItems(menu);
    add5SecondaryMenuItems(menu);
    this.addSubMenu(menu);
    return true;
  }

  private void addRegularMenuItems(Menu menu) {
    int base = Menu.FIRST; // value is 1

    MenuItem item1 = menu.add(base, base, base, "append");
    menu.add(base, base + 1, base + 1, "item 2");
    menu.add(base, base + 2, base + 2, "clear");

    menu.add(base, base + 3, base + 3, "hide secondary");
    menu.add(base, base + 4, base + 4, "show secondary");

    menu.add(base, base + 5, base + 5, "enable secondary");
    menu.add(base, base + 6, base + 6, "disable secondary");

    menu.add(base, base + 7, base + 7, "check secondary");
    MenuItem item8 = menu
        .add(base, base + 8, base + 8, "uncheck secondary");
    item1.setIcon(R.drawable.icon);
    item8.setIcon(R.drawable.icon);
  }

  private void add5SecondaryMenuItems(Menu menu) {
    int base = Menu.CATEGORY_SECONDARY;

    menu.add(base, base + 1, base + 1, "sec. item 1");
    menu.add(base, base + 2, base + 2, "sec. item 2");
    menu.add(base, base + 3, base + 3, "sec. item 3");
    menu.add(base, base + 3, base + 3, "sec. item 4");
    menu.add(base, base + 4, base + 4, "sec. item 5");
  }

  private void addSubMenu(Menu menu) {
    int base = Menu.FIRST + 100;
    SubMenu sm = menu.addSubMenu(base, base + 1, Menu.NONE, "submenu");
    MenuItem item1 = sm.add(base, base + 2, base + 2, "sub item1");

    sm.add(base, base + 3, base + 3, "sub item2");
    sm.add(base, base + 4, base + 4, "sub item3");
    item1.setIcon(R.drawable.icon);
    sm.setIcon(R.drawable.icon);
  }

  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == 1) {
      appendText("\nhello");
    } else if (item.getItemId() == 2) {
      appendText("\nitem2");
    } else if (item.getItemId() == 3) {
      emptyText();
    } else if (item.getItemId() == 4) {
      // hide secondary
      this.appendMenuItemText(item);
      this.myMenu.setGroupVisible(Menu.CATEGORY_SECONDARY, false);
    } else if (item.getItemId() == 5) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupVisible(Menu.CATEGORY_SECONDARY, true);
    } else if (item.getItemId() == 6) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupEnabled(Menu.CATEGORY_SECONDARY, true);
    } else if (item.getItemId() == 7) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupEnabled(Menu.CATEGORY_SECONDARY, false);
    } else if (item.getItemId() == 8) {
      this.appendMenuItemText(item);
      this.myMenu.setGroupCheckable(Menu.CATEGORY_SECONDARY, true, false);
    } else if (item.getItemId() == 9) {
      this.appendMenuItemText(item);
      this.myMenu
          .setGroupCheckable(Menu.CATEGORY_SECONDARY, false, false);
    } else {
      this.appendMenuItemText(item);
    }
    return true;
  }

  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
      ContextMenuInfo menuInfo) {
    menu.setHeaderTitle("Sample menu");
    menu.add(200, 200, 200, "item1");
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
    this.appendMenuItemText(item);
    return true;
  }

  private void loadXMLMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater(); // from activity
    inflater.inflate(R.menu.my_menu, menu);
  }

  private TextView getTextView() {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    return tv;
  }

  public void appendText(String text) {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText(tv.getText() + text);
  }

  private void appendMenuItemText(MenuItem menuItem) {
    String title = menuItem.getTitle().toString();
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText(tv.getText() + "\n" + title + ":" + menuItem.getItemId());
  }

  private void emptyText() {
    TextView tv = (TextView) this.findViewById(R.id.textViewId);
    tv.setText("");
  }
}

//main.xml
<?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:id="@+id/textViewId"  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
</LinearLayout>

//menu/my_menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This group uses the default category. -->
    <group android:id="@+id/menuGroup_Main">

        <item android:id="@+id/menu_testPick"
            android:orderInCategory="5"
            android:title="Test Pick" />
            
        <item android:id="@+id/menu_testGetContent"
            android:orderInCategory="5"
            android:title="Test Get Content" />
            
        <item android:id="@+id/menu_clear"
            android:orderInCategory="10"
            android:title="clear" />
            
        <item android:id="@+id/menu_dial"
            android:orderInCategory="7"
            android:title="dial" />
            
        <item android:id="@+id/menu_test"
            android:orderInCategory="4"
            android:title="@+string/test" />
            
        <item android:id="@+id/menu_show_browser"
            android:orderInCategory="5"
            android:title="show browser" />
    </group>
</menu>

Get Menu title

  
package app.test;

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

public class Test extends Activity 
{
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
      super.onCreateOptionsMenu(menu);
        MenuInflater inflater = getMenuInflater(); //from activity
        inflater.inflate(R.menu.my_menu, menu);
      return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
    {
      appendMenuItemText(item);
      if (item.getItemId() == R.id.menu_clear)
      {
        this.emptyText();
        return true;
      }
      return true;
    }
    
    private TextView getTextView()
    {
        return (TextView)this.findViewById(R.id.text1);
    }
    public void appendText(String abc)
    {
        TextView tv = getTextView(); 
        tv.setText(tv.getText() + "\n" + abc);
    }
    
    private void appendMenuItemText(MenuItem menuItem)
    {
       String title = menuItem.getTitle().toString();
       TextView tv = getTextView(); 
       tv.setText(tv.getText() + "\n" + title);
    }
    private void emptyText()
    {
          TextView tv = getTextView();
          tv.setText("");
    }
}

//main.xml

<?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:id="@+id/text1"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="Your debug will appear here"
    />
</LinearLayout>
//my_menu.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- This group uses the default category. -->
    <group android:id="@+id/menuGroup_Main">
        <item android:id="@+id/menu_clear"
       android:title="clear" />
       
        <item android:id="@+id/menu_testlib_1"
            android:title="Lib Test Menu1" />
            
        <item android:id="@+id/menu_testlib_2"
            android:title="Lib Test Menu2" />
    </group>
</menu>
onOptionsItemSelected/onPrepareOptionsMenu/onCreateOptionsMenu Event
package app.test;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Picture;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

//Need the following import to get access to the app resources, since this
//class is in a sub-package.


/**
* Demonstrates the handling of touch screen and trackball events to
* implement a simple painting app.
*/
public class Test extends GraphicsActivity {
  /** Used as a pulse to gradually fade the contents of the window. */
  private static final int FADE_MSG = 1;

  /** Menu ID for the command to clear the window. */
  private static final int CLEAR_ID = Menu.FIRST;
  /** Menu ID for the command to toggle fading. */
  private static final int FADE_ID = Menu.FIRST+1;

  /** How often to fade the contents of the window (in ms). */
  private static final int FADE_DELAY = 100;

  /** The view responsible for drawing the window. */
  MyView mView;
  /** Is fading mode enabled? */
  boolean mFading;

  @Override protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);

      // Create and attach the view that is responsible for painting.
      mView = new MyView(this);
      setContentView(mView);
      mView.requestFocus();

      // Restore the fading option if we are being thawed from a
      // previously saved state.  Note that we are not currently remembering
      // the contents of the bitmap.
      mFading = savedInstanceState != null ? savedInstanceState.getBoolean("fading", true) : true;
  }

  @Override public boolean onCreateOptionsMenu(Menu menu) {
      menu.add(0, CLEAR_ID, 0, "Clear");
      menu.add(0, FADE_ID, 0, "Fade").setCheckable(true);
      return super.onCreateOptionsMenu(menu);
  }

  @Override public boolean onPrepareOptionsMenu(Menu menu) {
      menu.findItem(FADE_ID).setChecked(mFading);
      return super.onPrepareOptionsMenu(menu);
  }

  @Override public boolean onOptionsItemSelected(MenuItem item) {
      switch (item.getItemId()) {
          case CLEAR_ID:
              mView.clear();
              return true;
          case FADE_ID:
              mFading = !mFading;
              if (mFading) {
                  startFading();
              } else {
                  stopFading();
              }
              return true;
          default:
              return super.onOptionsItemSelected(item);
      }
  }

  @Override protected void onResume() {
      super.onResume();
      // If fading mode is enabled, then as long as we are resumed we want
      // to run pulse to fade the contents.
      if (mFading) {
          startFading();
      }
  }

  @Override protected void onSaveInstanceState(Bundle outState) {
      super.onSaveInstanceState(outState);
      // Save away the fading state to restore if needed later.  Note that
      // we do not currently save the contents of the display.
      outState.putBoolean("fading", mFading);
  }

  @Override protected void onPause() {
      super.onPause();
      // Make sure to never run the fading pulse while we are paused or
      // stopped.
      stopFading();
  }

  /**
   * Start up the pulse to fade the screen, clearing any existing pulse to
   * ensure that we don't have multiple pulses running at a time.
   */
  void startFading() {
      mHandler.removeMessages(FADE_MSG);
      mHandler.sendMessageDelayed(
              mHandler.obtainMessage(FADE_MSG), FADE_DELAY);
  }

  /**
   * Stop the pulse to fade the screen.
   */
  void stopFading() {
      mHandler.removeMessages(FADE_MSG);
  }

  private Handler mHandler = new Handler() {
      @Override public void handleMessage(Message msg) {
          switch (msg.what) {
              // Upon receiving the fade pulse, we have the view perform a
              // fade and then enqueue a new message to pulse at the desired
              // next time.
              case FADE_MSG: {
                  mView.fade();
                  mHandler.sendMessageDelayed(
                          mHandler.obtainMessage(FADE_MSG), FADE_DELAY);
                  break;
              }
              default:
                  super.handleMessage(msg);
          }
      }
  };

  public class MyView extends View {
      private static final int FADE_ALPHA = 0x06;
      private static final int MAX_FADE_STEPS = 256/FADE_ALPHA + 4;
      private static final int TRACKBALL_SCALE = 10;

      private Bitmap mBitmap;
      private Canvas mCanvas;
      private final Rect mRect = new Rect();
      private final Paint mPaint;
      private final Paint mFadePaint;
      private float mCurX;
      private float mCurY;
      private int mFadeSteps = MAX_FADE_STEPS;

      public MyView(Context c) {
          super(c);
          setFocusable(true);
          mPaint = new Paint();
          mPaint.setAntiAlias(true);
          mPaint.setARGB(255, 255, 255, 255);
          mFadePaint = new Paint();
          mFadePaint.setDither(true);
          mFadePaint.setARGB(FADE_ALPHA, 0, 0, 0);
      }

      public void clear() {
          if (mCanvas != null) {
              mPaint.setARGB(0xff, 0, 0, 0);
              mCanvas.drawPaint(mPaint);
              invalidate();
              mFadeSteps = MAX_FADE_STEPS;
          }
      }

      public void fade() {
          if (mCanvas != null && mFadeSteps < MAX_FADE_STEPS) {
              mCanvas.drawPaint(mFadePaint);
              invalidate();
              mFadeSteps++;
          }
      }

      @Override protected void onSizeChanged(int w, int h, int oldw,
              int oldh) {
          int curW = mBitmap != null ? mBitmap.getWidth() : 0;
          int curH = mBitmap != null ? mBitmap.getHeight() : 0;
          if (curW >= w && curH >= h) {
              return;
          }

          if (curW < w) curW = w;
          if (curH < h) curH = h;

          Bitmap newBitmap = Bitmap.createBitmap(curW, curH,
                                                 Bitmap.Config.RGB_565);
          Canvas newCanvas = new Canvas();
          newCanvas.setBitmap(newBitmap);
          if (mBitmap != null) {
              newCanvas.drawBitmap(mBitmap, 0, 0, null);
          }
          mBitmap = newBitmap;
          mCanvas = newCanvas;
          mFadeSteps = MAX_FADE_STEPS;
      }

      @Override protected void onDraw(Canvas canvas) {
          if (mBitmap != null) {
              canvas.drawBitmap(mBitmap, 0, 0, null);
          }
      }

      @Override public boolean onTrackballEvent(MotionEvent event) {
          int N = event.getHistorySize();
          final float scaleX = event.getXPrecision() * TRACKBALL_SCALE;
          final float scaleY = event.getYPrecision() * TRACKBALL_SCALE;
          for (int i=0; i<N; i++) {
              //Log.i("TouchPaint", "Intermediate trackball #" + i
              //        + ": x=" + event.getHistoricalX(i)
              //        + ", y=" + event.getHistoricalY(i));
              mCurX += event.getHistoricalX(i) * scaleX;
              mCurY += event.getHistoricalY(i) * scaleY;
              drawPoint(mCurX, mCurY, 1.0f, 16.0f);
          }
          //Log.i("TouchPaint", "Trackball: x=" + event.getX()
          //        + ", y=" + event.getY());
          mCurX += event.getX() * scaleX;
          mCurY += event.getY() * scaleY;
          drawPoint(mCurX, mCurY, 1.0f, 16.0f);
          return true;
      }

      @Override public boolean onTouchEvent(MotionEvent event) {
          int action = event.getActionMasked();
          if (action != MotionEvent.ACTION_UP && action != MotionEvent.ACTION_CANCEL) {
              int N = event.getHistorySize();
              int P = event.getPointerCount();
              for (int i = 0; i < N; i++) {
                  for (int j = 0; j < P; j++) {
                      mCurX = event.getHistoricalX(j, i);
                      mCurY = event.getHistoricalY(j, i);
                      drawPoint(mCurX, mCurY,
                              event.getHistoricalPressure(j, i),
                              event.getHistoricalTouchMajor(j, i));
                  }
              }
              for (int j = 0; j < P; j++) {
                  mCurX = event.getX(j);
                  mCurY = event.getY(j);
                  drawPoint(mCurX, mCurY, event.getPressure(j), event.getTouchMajor(j));
              }
          }
          return true;
      }

      private void drawPoint(float x, float y, float pressure, float width) {
          //Log.i("TouchPaint", "Drawing: " + x + "x" + y + " p="
          //        + pressure + " width=" + width);
          if (width < 1) width = 1;
          if (mBitmap != null) {
              float radius = width / 2;
              int pressureLevel = (int)(pressure * 255);
              mPaint.setARGB(pressureLevel, 255, 255, 255);
              mCanvas.drawCircle(x, y, radius, mPaint);
              mRect.set((int) (x - radius - 2), (int) (y - radius - 2),
                      (int) (x + radius + 2), (int) (y + radius + 2));
              invalidate(mRect);
          }
          mFadeSteps = 0;
      }
  }
}

class GraphicsActivity extends Activity {
  // set to true to test Picture
  private static final boolean TEST_PICTURE = false;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  }

  @Override
  public void setContentView(View view) {
    if (TEST_PICTURE) {
      ViewGroup vg = new PictureLayout(this);
      vg.addView(view);
      view = vg;
    }

    super.setContentView(view);
  }
}

class PictureLayout extends ViewGroup {
  private final Picture mPicture = new Picture();

  public PictureLayout(Context context) {
    super(context);
  }

  public PictureLayout(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  @Override
  public void addView(View child) {
    if (getChildCount() > 1) {
      throw new IllegalStateException(
          "PictureLayout can host only one direct child");
    }

    super.addView(child);
  }

  @Override
  public void addView(View child, int index) {
    if (getChildCount() > 1) {
      throw new IllegalStateException(
          "PictureLayout can host only one direct child");
    }

    super.addView(child, index);
  }

  @Override
  public void addView(View child, LayoutParams params) {
    if (getChildCount() > 1) {
      throw new IllegalStateException(
          "PictureLayout can host only one direct child");
    }

    super.addView(child, params);
  }

  @Override
  public void addView(View child, int index, LayoutParams params) {
    if (getChildCount() > 1) {
      throw new IllegalStateException(
          "PictureLayout can host only one direct child");
    }

    super.addView(child, index, params);
  }

  @Override
  protected LayoutParams generateDefaultLayoutParams() {
    return new LayoutParams(LayoutParams.MATCH_PARENT,
        LayoutParams.MATCH_PARENT);
  }

  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    final int count = getChildCount();

    int maxHeight = 0;
    int maxWidth = 0;

    for (int i = 0; i < count; i++) {
      final View child = getChildAt(i);
      if (child.getVisibility() != GONE) {
        measureChild(child, widthMeasureSpec, heightMeasureSpec);
      }
    }

    maxWidth += getPaddingLeft() + getPaddingRight();
    maxHeight += getPaddingTop() + getPaddingBottom();

    Drawable drawable = getBackground();
    if (drawable != null) {
      maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
      maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
    }

    setMeasuredDimension(resolveSize(maxWidth, widthMeasureSpec),
        resolveSize(maxHeight, heightMeasureSpec));
  }

  private void drawPict(Canvas canvas, int x, int y, int w, int h, float sx,
      float sy) {
    canvas.save();
    canvas.translate(x, y);
    canvas.clipRect(0, 0, w, h);
    canvas.scale(0.5f, 0.5f);
    canvas.scale(sx, sy, w, h);
    canvas.drawPicture(mPicture);
    canvas.restore();
  }

  @Override
  protected void dispatchDraw(Canvas canvas) {
    super.dispatchDraw(mPicture.beginRecording(getWidth(), getHeight()));
    mPicture.endRecording();

    int x = getWidth() / 2;
    int y = getHeight() / 2;

    if (false) {
      canvas.drawPicture(mPicture);
    } else {
      drawPict(canvas, 0, 0, x, y, 1, 1);
      drawPict(canvas, x, 0, x, y, -1, 1);
      drawPict(canvas, 0, y, x, y, 1, -1);
      drawPict(canvas, x, y, x, y, -1, -1);
    }
  }

  @Override
  public ViewParent invalidateChildInParent(int[] location, Rect dirty) {
    location[0] = getLeft();
    location[1] = getTop();
    dirty.set(0, 0, getWidth(), getHeight());
    return getParent();
  }

  @Override
  protected void onLayout(boolean changed, int l, int t, int r, int b) {
    final int count = super.getChildCount();

    for (int i = 0; i < count; i++) {
      final View child = getChildAt(i);
      if (child.getVisibility() != GONE) {
        final int childLeft = getPaddingLeft();
        final int childTop = getPaddingTop();
        child.layout(childLeft, childTop,
            childLeft + child.getMeasuredWidth(),
            childTop + child.getMeasuredHeight());

      }
    }
  }
}

Basics of the Action Bar and how it interoperates with the standard options menu.

package app.test;

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

/**
 * This demonstrates the basics of the Action Bar and how it interoperates with the
 * standard options menu. This demo is for informative purposes only; see ActionBarUsage for
 * an example of using the Action Bar in a more idiomatic manner.
 */
public class Test extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // The Action Bar is a window feature. The feature must be requested
        // before setting a content view. Normally this is set automatically
        // by your Activity's theme in your manifest. The provided system
        // theme Theme.WithActionBar enables this for you. Use it as you would
        // use Theme.NoTitleBar. You can add an Action Bar to your own themes
        // by adding the element <item name="android:windowActionBar">true</item>
        // to your style definition.
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Menu items default to never show in the action bar. On most devices this means
        // they will show in the standard options menu panel when the menu button is pressed.
        // On xlarge-screen devices a "More" button will appear in the far right of the
        // Action Bar that will display remaining items in a cascading menu.
        menu.add("Normal item");

        MenuItem actionItem = menu.add("Action Button");

        // Items that show as actions should favor the "if room" setting, which will
        // prevent too many buttons from crowding the bar. Extra items will show in the
        // overflow area.
        actionItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

        // Items that show as actions are strongly encouraged to use an icon.
        // These icons are shown without a text description, and therefore should
        // be sufficiently descriptive on their own.
        actionItem.setIcon(android.R.drawable.ic_menu_share);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Toast.makeText(this, "Selected Item: " + item.getTitle(), Toast.LENGTH_SHORT).show();
        return true;
    }
}

Demonstration of displaying a context menu from a fragment.

package com.example.android.apis.app;

import com.example.android.apis.R;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ContextMenu.ContextMenuInfo;

/**
 * Demonstration of displaying a context menu from a fragment.
 */
public class FragmentContextMenu extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create the list fragment and add it as our sole content.
        ContextMenuFragment content = new ContextMenuFragment();
        getFragmentManager().beginTransaction().add(android.R.id.content, content).commit();
    }

    public static class ContextMenuFragment extends Fragment {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View root = inflater.inflate(R.layout.fragment_context_menu, container, false);
            registerForContextMenu(root.findViewById(R.id.long_press));
            return root;
        }

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
            super.onCreateContextMenu(menu, v, menuInfo);
            menu.add(Menu.NONE, R.id.a_item, Menu.NONE, "Menu A");
            menu.add(Menu.NONE, R.id.b_item, Menu.NONE, "Menu B");
        }

        @Override
        public boolean onContextItemSelected(MenuItem item) {
            switch (item.getItemId()) {
                case R.id.a_item:
                    Log.i("ContextMenu", "Item 1a was chosen");
                    return true;
                case R.id.b_item:
                    Log.i("ContextMenu", "Item 1b was chosen");
                    return true;
            }
            return super.onContextItemSelected(item);
        }
    }
}
//fragment_context_menu.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/fragment_context_menu_msg" />

    <Button android:id="@+id/long_press"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/long_press">
        <requestFocus />
    </Button>
    
</LinearLayout>

Demonstrates how fragments can participate in the options menu.

package com.example.android.apis.app;

import com.example.android.apis.R;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;

/**
 * Demonstrates how fragments can participate in the options menu.
 */
public class FragmentMenu extends Activity {
    Fragment mFragment1;
    Fragment mFragment2;
    CheckBox mCheckBox1;
    CheckBox mCheckBox2;

    // Update fragment visibility when check boxes are changed.
    final OnClickListener mClickListener = new OnClickListener() {
        public void onClick(View v) {
            updateFragmentVisibility();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_menu);
        
        // Make sure the two menu fragments are created.
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        mFragment1 = fm.findFragmentByTag("f1");
        if (mFragment1 == null) {
            mFragment1 = new MenuFragment();
            ft.add(mFragment1, "f1");
        }
        mFragment2 = fm.findFragmentByTag("f2");
        if (mFragment2 == null) {
            mFragment2 = new Menu2Fragment();
            ft.add(mFragment2, "f2");
        }
        ft.commit();
        
        // Watch check box clicks.
        mCheckBox1 = (CheckBox)findViewById(R.id.menu1);
        mCheckBox1.setOnClickListener(mClickListener);
        mCheckBox2 = (CheckBox)findViewById(R.id.menu2);
        mCheckBox2.setOnClickListener(mClickListener);
        
        // Make sure fragments start out with correct visibility.
        updateFragmentVisibility();
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        // Make sure fragments are updated after check box view state is restored.
        updateFragmentVisibility();
    }

    // Update fragment visibility based on current check box state.
    void updateFragmentVisibility() {
        FragmentTransaction ft = getFragmentManager().beginTransaction();
        if (mCheckBox1.isChecked()) ft.show(mFragment1);
        else ft.hide(mFragment1);
        if (mCheckBox2.isChecked()) ft.show(mFragment2);
        else ft.hide(mFragment2);
        ft.commit();
    }

    /**
     * A fragment that displays a menu.  This fragment happens to not
     * have a UI (it does not implement onCreateView), but it could also
     * have one if it wanted.
     */
    public static class MenuFragment extends Fragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            menu.add("Menu 1a").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
            menu.add("Menu 1b").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
    }

    /**
     * Second fragment with a menu.
     */
    public static class Menu2Fragment extends Fragment {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setHasOptionsMenu(true);
        }

        @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            menu.add("Menu 2").setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
        }
    }
}

//fragment_menu.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="8dp">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="@string/fragment_menu_msg" />

    <CheckBox android:id="@+id/menu1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:checked="true"
        android:text="@string/fragment1menu">
    </CheckBox>
    
    <CheckBox android:id="@+id/menu2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:checked="true"
        android:text="@string/fragment2menu">
    </CheckBox>
    
</LinearLayout>

Demonstrates inflating menus from XML.

package com.example.android.apis.app;

import com.example.android.apis.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MenuInflateFromXml extends Activity {
    /**
     * Different example menu resources.
     */
    private static final int sMenuExampleResources[] = {
        R.menu.title_only, R.menu.title_icon, R.menu.submenu, R.menu.groups,
        R.menu.checkable, R.menu.shortcuts, R.menu.order, R.menu.category_order,
        R.menu.visible, R.menu.disabled
    };
    
    /**
     * Names corresponding to the different example menu resources.
     */
    private static final String sMenuExampleNames[] = {
        "Title only", "Title and Icon", "Submenu", "Groups",
        "Checkable", "Shortcuts", "Order", "Category and Order",
        "Visible", "Disabled"
    };
   
    /**
     * Lets the user choose a menu resource.
     */
    private Spinner mSpinner;

    /**
     * Shown as instructions.
     */
    private TextView mInstructionsText;
    
    /**
     * Safe to hold on to this.
     */
    private Menu mMenu;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // Create a simple layout
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        
        // Create the spinner to allow the user to choose a menu XML
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, sMenuExampleNames); 
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        mSpinner = new Spinner(this);
        // When programmatically creating views, make sure to set an ID
        // so it will automatically save its instance state
        mSpinner.setId(R.id.spinner);
        mSpinner.setAdapter(adapter);
        
        // Add the spinner
        layout.addView(mSpinner,
                new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

        // Create help text
        mInstructionsText = new TextView(this);
        mInstructionsText.setText(getResources().getString(
                R.string.menu_from_xml_instructions_press_menu));
        
        // Add the help, make it look decent
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        lp.setMargins(10, 10, 10, 10);
        layout.addView(mInstructionsText, lp);
        
        // Set the layout as our content view
        setContentView(layout);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Hold on to this
        mMenu = menu;
        
        // Inflate the currently selected menu XML resource.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(sMenuExampleResources[mSpinner.getSelectedItemPosition()], menu);
        
        // Disable the spinner since we've already created the menu and the user
        // can no longer pick a different menu XML.
        mSpinner.setEnabled(false);
        
        // Change instructions
        mInstructionsText.setText(getResources().getString(
                R.string.menu_from_xml_instructions_go_back));
        
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            // For "Title only": Examples of matching an ID with one assigned in
            //                   the XML
            case R.id.jump:
                Toast.makeText(this, "Jump up in the air!", Toast.LENGTH_SHORT).show();
                return true;

            case R.id.dive:
                Toast.makeText(this, "Dive into the water!", Toast.LENGTH_SHORT).show();
                return true;

            // For "Groups": Toggle visibility of grouped menu items with
            //               nongrouped menu items
            case R.id.browser_visibility:
                // The refresh item is part of the browser group
                final boolean shouldShowBrowser = !mMenu.findItem(R.id.refresh).isVisible();
                mMenu.setGroupVisible(R.id.browser, shouldShowBrowser);
                break;
                
            case R.id.email_visibility:
                // The reply item is part of the email group
                final boolean shouldShowEmail = !mMenu.findItem(R.id.reply).isVisible();
                mMenu.setGroupVisible(R.id.email, shouldShowEmail);
                break;
                
            // Generic catch all for all the other menu resources
            default:
                // Don't toast text when a submenu is clicked
                if (!item.hasSubMenu()) {
                    Toast.makeText(this, item.getTitle(), Toast.LENGTH_SHORT).show();
                    return true;
                }
                break;
        }
        
        return false;
    }
    
    

}
//res\menu\category_order.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <!-- This group uses the default category. -->
    <group android:id="@+id/most_used_items">
    
        <item android:id="@+id/last_most_item"
            android:orderInCategory="10"
            android:title="@string/last_most_often" />
    
        <item android:id="@+id/middle_most_item"
            android:orderInCategory="7"
            android:title="@string/middle_most_often" />
    
        <item android:id="@+id/first_most_item"
            android:orderInCategory="4"
            android:title="@string/first_most_often" />
    
    </group>
    

    <group android:id="@+id/least_used_items"
        android:menuCategory="secondary">
        
        <item android:id="@+id/last_least_item"
            android:orderInCategory="3"
            android:title="@string/last_least_often" />
    
        <item android:id="@+id/middle_least_item"
            android:orderInCategory="2"
            android:title="@string/middle_least_often" />
    
        <item android:id="@+id/first_least_item"
            android:orderInCategory="0"
            android:title="@string/first_least_often" />
    
    </group>

</menu>



//res\menu\checkable.xml
<?xml version="1.0" encoding="utf-8"?>


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



    <item android:title="None">
        <menu>
            <!-- The none checkableBehavior is default, but we explicitly show it here. -->
            <group android:id="@+id/noncheckable_group"
                    android:checkableBehavior="none">
                <!-- Notice how these items inherit from the group. -->
                <item android:id="@+id/noncheckable_item_1"
                        android:title="@string/item_1" />
                <item android:id="@+id/noncheckable_item_2"
                        android:title="@string/item_2" />
                <item android:id="@+id/noncheckable_item_3"
                        android:title="@string/item_3" />
            </group>
        </menu>
    </item>

    <item android:title="All">
        <menu>
            <group android:id="@+id/checkable_group"
                    android:checkableBehavior="all">
                <!-- Notice how these items inherit from the group. -->
                <item android:id="@+id/checkable_item_1"
                        android:title="@string/item_1" />
                <item android:id="@+id/checkable_item_2"
                        android:title="@string/item_2"
                        android:checked="true" />
                <item android:id="@+id/checkable_item_3"
                        android:title="@string/item_3"
                        android:checked="true" />
            </group>
        </menu>
    </item>

    <item android:title="Single">
        <menu>
            <group android:id="@+id/exclusive_checkable_group"
                    android:checkableBehavior="single">
                <!-- Notice how these items inherit from the group. -->
                <item android:id="@+id/exclusive_checkable_item_1"
                        android:title="@string/item_1" />
                <item android:id="@+id/exclusive_checkable_item_2"
                        android:title="@string/item_2" />
                <item android:id="@+id/exclusive_checkable_item_3"
                        android:title="@string/item_3"
                        android:checked="true" />
            </group>
        </menu>
    </item>

    <item android:title="All without group">
        <menu>
            <!-- Notice how these items have each set. -->
            <item android:id="@+id/nongroup_checkable_item_1"
                    android:title="@string/item_1"
                    android:checkable="true" />
            <item android:id="@+id/nongroup_checkable_item_2"
                    android:title="@string/item_2"
                    android:checkable="true"
                    android:checked="true" />
            <item android:id="@+id/nongroup_checkable_item_3"
                    android:title="@string/item_3"
                    android:checkable="true"
                    android:checked="true" />
        </menu>
    </item>

</menu>



//res\menu\disabled.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <item android:id="@+id/enabled_item"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_2"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_2"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_3"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_3"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

    <item android:id="@+id/enabled_item_4"
        android:title="Enabled"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/disabled_item_4"
        android:title="Disabled"
        android:enabled="false"
        android:icon="@drawable/stat_sad" />

</menu>



//res\menu\groups.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <item android:id="@+id/browser_visibility"
        android:title="@string/browser_visibility" />

    <group android:id="@+id/browser">
    
        <item android:id="@+id/refresh"
            android:title="@string/browser_refresh" />
    
        <item android:id="@+id/bookmark"
            android:title="@string/browser_bookmark" />
    
    </group>

    <item android:id="@+id/email_visibility"
        android:title="@string/email_visibility" />

    <group android:id="@+id/email">
    
        <item android:id="@+id/reply"
            android:title="@string/email_reply" />
    
        <item android:id="@+id/forward"
            android:title="@string/email_forward" />
    
    </group>

</menu>



//res\menu\order.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <!-- These are in reverse order in this resource, but the orderInCategory attribute will
         order them for the menu (they all have the same default category). -->

    <item android:id="@+id/fourth_item"
        android:orderInCategory="3"
        android:title="Fourth" />

    <item android:id="@+id/third_item"
        android:orderInCategory="2"
        android:title="Third" />

    <item android:id="@+id/second_item"
        android:orderInCategory="1"
        android:title="Second" />

    <item android:id="@+id/first_item"
        android:orderInCategory="0"
        android:title="First" />

</menu>



//res\menu\shortcuts.xml
<?xml version="1.0" encoding="utf-8"?>

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

    <item android:id="@+id/invisible_item"
        android:visible="false"
        android:alphabeticShortcut="i"
        android:title="Invisible item" />

    <item android:id="@+id/a_item"
        android:alphabeticShortcut="a"
        android:title="Alvin" />

    <item android:id="@+id/b_item"
        android:alphabeticShortcut="b"
        android:title="Bart" />

    <item android:id="@+id/c_item"
        android:alphabeticShortcut="c"
        android:title="Chris" />

    <item android:id="@+id/d_item"
        android:alphabeticShortcut="d"
        android:title="David" />

    <item android:id="@+id/e_item"
        android:alphabeticShortcut="e"
        android:title="Eric" />

    <item android:id="@+id/f_item"
        android:alphabeticShortcut="f"
        android:title="Frank" />

    <item android:id="@+id/g_item"
        android:alphabeticShortcut="g"
        android:title="Gary" />

    <item android:id="@+id/h_item"
        android:alphabeticShortcut="h"
        android:title="Henry" />

    <item android:id="@+id/excl_item"
        android:alphabeticShortcut="!"
        android:title="Exclamation" />

</menu>



//res\menu\submenu.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <item android:title="Normal 1" />

    <item android:id="@+id/submenu"
        android:title="Emotions">

        <menu>        

            <item android:id="@+id/happy"
                android:title="Happy"
                android:icon="@drawable/stat_happy" />
        
            <item android:id="@+id/neutral"
                android:title="Neutral"
                android:icon="@drawable/stat_neutral" />
        
            <item android:id="@+id/sad"
                android:title="Sad"
                android:icon="@drawable/stat_sad" />
        
        </menu>
    
    </item>

    <item android:title="Normal 2" />

</menu>



//res\menu\title_icon.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <item android:id="@+id/happy"
        android:title="Happy"
        android:icon="@drawable/stat_happy" />

    <item android:id="@+id/neutral"
        android:title="Neutral"
        android:icon="@drawable/stat_neutral" />

    <item android:id="@+id/sad"
        android:title="Sad"
        android:icon="@drawable/stat_sad" />

</menu>



//res\menu\title_only.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <item android:id="@+id/jump"
        android:title="@string/jump" />

    <item android:id="@+id/dive"
        android:title="@string/dive" />

</menu>



//res\menu\visible.xml
<?xml version="1.0" encoding="utf-8"?>


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

    <item android:id="@+id/visible_item"
        android:title="Visible"
        android:alphabeticShortcut="a" />

    <item android:id="@+id/hidden_item"
        android:title="Hidden"
        android:visible="false"
        android:alphabeticShortcut="b" />

    <group android:id="@+id/hidden_group"
        android:visible="false">
    
        <item android:id="@+id/hidden_by_group"
            android:title="Hidden by group"
            android:alphabeticShortcut="c" />
    
    </group>

</menu>

Usage of SearchView in an ActionBar as a menu item

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.Activity;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.SearchView;
import android.widget.TextView;

import java.util.List;


public class SearchViewActionBar extends Activity implements SearchView.OnQueryTextListener,
        SearchView.OnCloseListener, Button.OnClickListener {

    private SearchView mSearchView;
    private Button mOpenButton;
    private Button mCloseButton;
    private TextView mStatusView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);

        setContentView(R.layout.searchview_actionbar);

        mStatusView = (TextView) findViewById(R.id.status_text);
        mOpenButton = (Button) findViewById(R.id.open_button);
        mCloseButton = (Button) findViewById(R.id.close_button);
        mOpenButton.setOnClickListener(this);
        mCloseButton.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.searchview_in_menu, menu);
        mSearchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
        setupSearchView();

        return true;
    }

    private void setupSearchView() {

        mSearchView.setIconifiedByDefault(true);

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
        if (searchManager != null) {
            List<SearchableInfo> searchables = searchManager.getSearchablesInGlobalSearch();

            // Try to use the "applications" global search provider
            SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
            for (SearchableInfo inf : searchables) {
                if (inf.getSuggestAuthority() != null
                        && inf.getSuggestAuthority().startsWith("applications")) {
                    info = inf;
                }
            }
            mSearchView.setSearchableInfo(info);
        }

        mSearchView.setOnQueryTextListener(this);
        mSearchView.setOnCloseListener(this);
    }

    public boolean onQueryTextChange(String newText) {
        mStatusView.setText("Query = " + newText);
        return false;
    }

    public boolean onQueryTextSubmit(String query) {
        mStatusView.setText("Query = " + query + " : submitted");
        return false;
    }

    public boolean onClose() {
        mStatusView.setText("Closed!");
        return false;
    }

    public void onClick(View view) {
        if (view == mCloseButton) {
            mSearchView.setIconified(true);
        } else if (view == mOpenButton) {
            mSearchView.setIconified(false);
        }
    }
}

//layout/searchview_actionbar.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

    <Button
            android:id="@+id/open_button"
            android:text="@string/open_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
        />

    <Button
            android:id="@+id/close_button"
            android:text="@string/close_search"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"
        />

    <TextView
            android:id="@+id/status_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center_horizontal"/>

</LinearLayout>

//menu/searchview_in_menu.xml

<?xml version="1.0" encoding="utf-8"?>

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/action_search"
          android:title="@string/action_bar_search"
          android:icon="@android:drawable/ic_menu_search"
          android:showAsAction="always"
          android:actionViewClass="android.widget.SearchView" />
</menu>

This demo illustrates the use of CHOICE_MODE_MULTIPLE_MODAL

package com.example.android.apis.view;

import com.example.android.apis.R;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class List16 extends ListActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ListView lv = getListView();
        lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
        lv.setMultiChoiceModeListener(new ModeCallback());
        setListAdapter(new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_activated_1, Cheeses.sCheeseStrings));
    }
    
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        getActionBar().setSubtitle("Long press to start selection");
    }
    
    private class ModeCallback implements ListView.MultiChoiceModeListener {

        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.list_select_menu, menu);
            mode.setTitle("Select Items");
            return true;
        }

        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return true;
        }

        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.share:
                Toast.makeText(List16.this, "Shared " + getListView().getCheckedItemCount() +
                        " items", Toast.LENGTH_SHORT).show();
                mode.finish();
                break;
            default:
                Toast.makeText(List16.this, "Clicked " + item.getTitle(),
                        Toast.LENGTH_SHORT).show();
                break;
            }
            return true;
        }

        public void onDestroyActionMode(ActionMode mode) {
        }

        public void onItemCheckedStateChanged(ActionMode mode,
                int position, long id, boolean checked) {
            final int checkedCount = getListView().getCheckedItemCount();
            switch (checkedCount) {
                case 0:
                    mode.setSubtitle(null);
                    break;
                case 1:
                    mode.setSubtitle("One item selected");
                    break;
                default:
                    mode.setSubtitle("" + checkedCount + " items selected");
                    break;
            }
        }
        
    }
}
class Cheeses {

    public static final String[] sCheeseStrings = {
            "Abbaye de Belloc", "Abbaye du Mont des Cats", "Abertam", "Abondance", "Ackawi",
            "Acorn", "Adelost", "Affidelice au Chablis", "Afuega'l Pitu", "Airag", "Airedale",
            "Aisy Cendre", "Allgauer Emmentaler", "Alverca", "Ambert", "American Cheese",
            "Ami du Chambertin", "Anejo Enchilado", "Anneau du Vic-Bilh", "Anthoriro", "Appenzell",
            "Aragon", "Ardi Gasna", "Ardrahan", "Armenian String", "Aromes au Gene de Marc",
            "Asadero", "Asiago", "Aubisque Pyrenees", "Autun", "Avaxtskyr", "Baby Swiss",
            "Babybel", "Baguette Laonnaise", "Bakers", "Baladi", "Balaton", "Bandal", "Banon",
            "Barry's Bay Cheddar", "Basing", "Basket Cheese", "Bath Cheese", "Bavarian Bergkase",
            "Baylough", "Beaufort", "Beauvoorde", "Beenleigh Blue", "Beer Cheese", "Bel Paese",
            "Bergader", "Bergere Bleue", "Berkswell", "Beyaz Peynir", "Bierkase", "Bishop Kennedy",
            "Blarney", "Bleu d'Auvergne", "Bleu de Gex", "Bleu de Laqueuille",
            "Bleu de Septmoncel", "Bleu Des Causses", "Blue", "Blue Castello", "Blue Rathgore",
            "Blue Vein (Australian)", "Blue Vein Cheeses", "Bocconcini", "Bocconcini (Australian)",
            "Boeren Leidenkaas", "Bonchester", "Bosworth", "Bougon", "Boule Du Roves",
            "Boulette d'Avesnes", "Boursault", "Boursin", "Bouyssou", "Bra", "Braudostur",
            "Breakfast Cheese", "Brebis du Lavort", "Brebis du Lochois", "Brebis du Puyfaucon",
            "Bresse Bleu", "Brick", "Brie", "Brie de Meaux", "Brie de Melun", "Brillat-Savarin",
            "Brin", "Brin d' Amour", "Brin d'Amour", "Brinza (Burduf Brinza)",
            "Briquette de Brebis", "Briquette du Forez", "Broccio", "Broccio Demi-Affine",
            "Brousse du Rove", "Bruder Basil", "Brusselae Kaas (Fromage de Bruxelles)", "Bryndza",
            "Buchette d'Anjou", "Buffalo", "Burgos", "Butte", "Butterkase", "Button (Innes)",
            "Buxton Blue", "Cabecou", "Caboc", "Cabrales", "Cachaille", "Caciocavallo", "Caciotta",
            "Caerphilly", "Cairnsmore", "Calenzana", "Cambazola", "Camembert de Normandie",
            "Canadian Cheddar", "Canestrato", "Cantal", "Caprice des Dieux", "Capricorn Goat",
            "Capriole Banon", "Carre de l'Est", "Casciotta di Urbino", "Cashel Blue", "Castellano",
            "Castelleno", "Castelmagno", "Castelo Branco", "Castigliano", "Cathelain",
            "Celtic Promise", "Cendre d'Olivet", "Cerney", "Chabichou", "Chabichou du Poitou",
            "Chabis de Gatine", "Chaource", "Charolais", "Chaumes", "Cheddar",
            "Cheddar Clothbound", "Cheshire", "Chevres", "Chevrotin des Aravis", "Chontaleno",
            "Civray", "Coeur de Camembert au Calvados", "Coeur de Chevre", "Colby", "Cold Pack",
            "Comte", "Coolea", "Cooleney", "Coquetdale", "Corleggy", "Cornish Pepper",
            "Cotherstone", "Cotija", "Cottage Cheese", "Cottage Cheese (Australian)",
            "Cougar Gold", "Coulommiers", "Coverdale", "Crayeux de Roncq", "Cream Cheese",
            "Cream Havarti", "Crema Agria", "Crema Mexicana", "Creme Fraiche", "Crescenza",
            "Croghan", "Crottin de Chavignol", "Crottin du Chavignol", "Crowdie", "Crowley",
            "Cuajada", "Curd", "Cure Nantais", "Curworthy", "Cwmtawe Pecorino",
            "Cypress Grove Chevre", "Danablu (Danish Blue)", "Danbo", "Danish Fontina",
            "Daralagjazsky", "Dauphin", "Delice des Fiouves", "Denhany Dorset Drum", "Derby",
            "Dessertnyj Belyj", "Devon Blue", "Devon Garland", "Dolcelatte", "Doolin",
            "Doppelrhamstufel", "Dorset Blue Vinney", "Double Gloucester", "Double Worcester",
            "Dreux a la Feuille", "Dry Jack", "Duddleswell", "Dunbarra", "Dunlop", "Dunsyre Blue",
            "Duroblando", "Durrus", "Dutch Mimolette (Commissiekaas)", "Edam", "Edelpilz",
            "Emental Grand Cru", "Emlett", "Emmental", "Epoisses de Bourgogne", "Esbareich",
            "Esrom", "Etorki", "Evansdale Farmhouse Brie", "Evora De L'Alentejo", "Exmoor Blue",
            "Explorateur", "Feta", "Feta (Australian)", "Figue", "Filetta", "Fin-de-Siecle",
            "Finlandia Swiss", "Finn", "Fiore Sardo", "Fleur du Maquis", "Flor de Guia",
            "Flower Marie", "Folded", "Folded cheese with mint", "Fondant de Brebis",
            "Fontainebleau", "Fontal", "Fontina Val d'Aosta", "Formaggio di capra", "Fougerus",
            "Four Herb Gouda", "Fourme d' Ambert", "Fourme de Haute Loire", "Fourme de Montbrison",
            "Fresh Jack", "Fresh Mozzarella", "Fresh Ricotta", "Fresh Truffles", "Fribourgeois",
            "Friesekaas", "Friesian", "Friesla", "Frinault", "Fromage a Raclette", "Fromage Corse",
            "Fromage de Montagne de Savoie", "Fromage Frais", "Fruit Cream Cheese",
            "Frying Cheese", "Fynbo", "Gabriel", "Galette du Paludier", "Galette Lyonnaise",
            "Galloway Goat's Milk Gems", "Gammelost", "Gaperon a l'Ail", "Garrotxa", "Gastanberra",
            "Geitost", "Gippsland Blue", "Gjetost", "Gloucester", "Golden Cross", "Gorgonzola",
            "Gornyaltajski", "Gospel Green", "Gouda", "Goutu", "Gowrie", "Grabetto", "Graddost",
            "Grafton Village Cheddar", "Grana", "Grana Padano", "Grand Vatel",
            "Grataron d' Areches", "Gratte-Paille", "Graviera", "Greuilh", "Greve",
            "Gris de Lille", "Gruyere", "Gubbeen", "Guerbigny", "Halloumi",
            "Halloumy (Australian)", "Haloumi-Style Cheese", "Harbourne Blue", "Havarti",
            "Heidi Gruyere", "Hereford Hop", "Herrgardsost", "Herriot Farmhouse", "Herve",
            "Hipi Iti", "Hubbardston Blue Cow", "Hushallsost", "Iberico", "Idaho Goatster",
            "Idiazabal", "Il Boschetto al Tartufo", "Ile d'Yeu", "Isle of Mull", "Jarlsberg",
            "Jermi Tortes", "Jibneh Arabieh", "Jindi Brie", "Jubilee Blue", "Juustoleipa",
            "Kadchgall", "Kaseri", "Kashta", "Kefalotyri", "Kenafa", "Kernhem", "Kervella Affine",
            "Kikorangi", "King Island Cape Wickham Brie", "King River Gold", "Klosterkaese",
            "Knockalara", "Kugelkase", "L'Aveyronnais", "L'Ecir de l'Aubrac", "La Taupiniere",
            "La Vache Qui Rit", "Laguiole", "Lairobell", "Lajta", "Lanark Blue", "Lancashire",
            "Langres", "Lappi", "Laruns", "Lavistown", "Le Brin", "Le Fium Orbo", "Le Lacandou",
            "Le Roule", "Leafield", "Lebbene", "Leerdammer", "Leicester", "Leyden", "Limburger",
            "Lincolnshire Poacher", "Lingot Saint Bousquet d'Orb", "Liptauer", "Little Rydings",
            "Livarot", "Llanboidy", "Llanglofan Farmhouse", "Loch Arthur Farmhouse",
            "Loddiswell Avondale", "Longhorn", "Lou Palou", "Lou Pevre", "Lyonnais", "Maasdam",
            "Macconais", "Mahoe Aged Gouda", "Mahon", "Malvern", "Mamirolle", "Manchego",
            "Manouri", "Manur", "Marble Cheddar", "Marbled Cheeses", "Maredsous", "Margotin",
            "Maribo", "Maroilles", "Mascares", "Mascarpone", "Mascarpone (Australian)",
            "Mascarpone Torta", "Matocq", "Maytag Blue", "Meira", "Menallack Farmhouse",
            "Menonita", "Meredith Blue", "Mesost", "Metton (Cancoillotte)", "Meyer Vintage Gouda",
            "Mihalic Peynir", "Milleens", "Mimolette", "Mine-Gabhar", "Mini Baby Bells", "Mixte",
            "Molbo", "Monastery Cheeses", "Mondseer", "Mont D'or Lyonnais", "Montasio",
            "Monterey Jack", "Monterey Jack Dry", "Morbier", "Morbier Cru de Montagne",
            "Mothais a la Feuille", "Mozzarella", "Mozzarella (Australian)",
            "Mozzarella di Bufala", "Mozzarella Fresh, in water", "Mozzarella Rolls", "Munster",
            "Murol", "Mycella", "Myzithra", "Naboulsi", "Nantais", "Neufchatel",
            "Neufchatel (Australian)", "Niolo", "Nokkelost", "Northumberland", "Oaxaca",
            "Olde York", "Olivet au Foin", "Olivet Bleu", "Olivet Cendre",
            "Orkney Extra Mature Cheddar", "Orla", "Oschtjepka", "Ossau Fermier", "Ossau-Iraty",
            "Oszczypek", "Oxford Blue", "P'tit Berrichon", "Palet de Babligny", "Paneer", "Panela",
            "Pannerone", "Pant ys Gawn", "Parmesan (Parmigiano)", "Parmigiano Reggiano",
            "Pas de l'Escalette", "Passendale", "Pasteurized Processed", "Pate de Fromage",
            "Patefine Fort", "Pave d'Affinois", "Pave d'Auge", "Pave de Chirac", "Pave du Berry",
            "Pecorino", "Pecorino in Walnut Leaves", "Pecorino Romano", "Peekskill Pyramid",
            "Pelardon des Cevennes", "Pelardon des Corbieres", "Penamellera", "Penbryn",
            "Pencarreg", "Perail de Brebis", "Petit Morin", "Petit Pardou", "Petit-Suisse",
            "Picodon de Chevre", "Picos de Europa", "Piora", "Pithtviers au Foin",
            "Plateau de Herve", "Plymouth Cheese", "Podhalanski", "Poivre d'Ane", "Polkolbin",
            "Pont l'Eveque", "Port Nicholson", "Port-Salut", "Postel", "Pouligny-Saint-Pierre",
            "Pourly", "Prastost", "Pressato", "Prince-Jean", "Processed Cheddar", "Provolone",
            "Provolone (Australian)", "Pyengana Cheddar", "Pyramide", "Quark",
            "Quark (Australian)", "Quartirolo Lombardo", "Quatre-Vents", "Quercy Petit",
            "Queso Blanco", "Queso Blanco con Frutas --Pina y Mango", "Queso de Murcia",
            "Queso del Montsec", "Queso del Tietar", "Queso Fresco", "Queso Fresco (Adobera)",
            "Queso Iberico", "Queso Jalapeno", "Queso Majorero", "Queso Media Luna",
            "Queso Para Frier", "Queso Quesadilla", "Rabacal", "Raclette", "Ragusano", "Raschera",
            "Reblochon", "Red Leicester", "Regal de la Dombes", "Reggianito", "Remedou",
            "Requeson", "Richelieu", "Ricotta", "Ricotta (Australian)", "Ricotta Salata", "Ridder",
            "Rigotte", "Rocamadour", "Rollot", "Romano", "Romans Part Dieu", "Roncal", "Roquefort",
            "Roule", "Rouleau De Beaulieu", "Royalp Tilsit", "Rubens", "Rustinu", "Saaland Pfarr",
            "Saanenkaese", "Saga", "Sage Derby", "Sainte Maure", "Saint-Marcellin",
            "Saint-Nectaire", "Saint-Paulin", "Salers", "Samso", "San Simon", "Sancerre",
            "Sap Sago", "Sardo", "Sardo Egyptian", "Sbrinz", "Scamorza", "Schabzieger", "Schloss",
            "Selles sur Cher", "Selva", "Serat", "Seriously Strong Cheddar", "Serra da Estrela",
            "Sharpam", "Shelburne Cheddar", "Shropshire Blue", "Siraz", "Sirene", "Smoked Gouda",
            "Somerset Brie", "Sonoma Jack", "Sottocenare al Tartufo", "Soumaintrain",
            "Sourire Lozerien", "Spenwood", "Sraffordshire Organic", "St. Agur Blue Cheese",
            "Stilton", "Stinking Bishop", "String", "Sussex Slipcote", "Sveciaost", "Swaledale",
            "Sweet Style Swiss", "Swiss", "Syrian (Armenian String)", "Tala", "Taleggio", "Tamie",
            "Tasmania Highland Chevre Log", "Taupiniere", "Teifi", "Telemea", "Testouri",
            "Tete de Moine", "Tetilla", "Texas Goat Cheese", "Tibet", "Tillamook Cheddar",
            "Tilsit", "Timboon Brie", "Toma", "Tomme Brulee", "Tomme d'Abondance",
            "Tomme de Chevre", "Tomme de Romans", "Tomme de Savoie", "Tomme des Chouans", "Tommes",
            "Torta del Casar", "Toscanello", "Touree de L'Aubier", "Tourmalet",
            "Trappe (Veritable)", "Trois Cornes De Vendee", "Tronchon", "Trou du Cru", "Truffe",
            "Tupi", "Turunmaa", "Tymsboro", "Tyn Grug", "Tyning", "Ubriaco", "Ulloa",
            "Vacherin-Fribourgeois", "Valencay", "Vasterbottenost", "Venaco", "Vendomois",
            "Vieux Corse", "Vignotte", "Vulscombe", "Waimata Farmhouse Blue",
            "Washed Rind Cheese (Australian)", "Waterloo", "Weichkaese", "Wellington",
            "Wensleydale", "White Stilton", "Whitestone Farmhouse", "Wigmore", "Woodside Cabecou",
            "Xanadu", "Xynotyro", "Yarg Cornish", "Yarra Valley Pyramid", "Yorkshire Blue",
            "Zamorano", "Zanetti Grana Padano", "Zanetti Parmigiano Reggiano"
    };

}

//menu/list_select_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/share"
          android:title="@string/share"
          android:icon="@android:drawable/ic_menu_share"
          android:showAsAction="always" />
</menu>