How to add a context menu in Android

23 Jan
  1. Create an Android XML file of Menu type
  2. Add menu options as you preferred. Each menu option should be indicated as <item> XML element.
  3. This is my context_menu.xml file.
    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="" >
    <item android:id="@+id/item1"   android:title="option1"></item>
    <item android:id="@+id/item2"   android:title="option2"></item>
  4. Override onCreateContextMenu and onContextItemSelected in your file
    Add a button in main.xml to respond our context menu.

    import android.os.Bundle;
    import android.util.Log;
    import android.view.ContextMenu;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ContextMenu.ContextMenuInfo;
    import android.widget.Button;
    public class ContextMenuActivity extends Activity {
    /** Called when the activity is first created. */
    public void onCreate(Bundle savedInstanceState) {
    Button b = (Button) findViewById(;
    public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
    MenuInflater inflator = getMenuInflater();
    inflator.inflate(, menu);
    public boolean onContextItemSelected(MenuItem item) {
    if(item.getItemId() ==
    Log.d("Edit", "Selected : Edit Option");
    if(item.getItemId() ==
    Log.d("Delete", "Selected : Delete Option");
    return super.onContextItemSelected(item);
Leave a comment

Posted by on January 23, 2012 in Android



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: