Blog

Android: Context menu example (on long press, gridview)

I received several requests regarding how I created a context menu (the menu activated on a long press) using a gridview and how to call functions such as saving a sound file from this. So I have created a quick example to explain this:

Tutorial

To implement a context menu (long press menu) you first need to include the following imports:

import android.view.ContextMenu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;

We start a very simple project, with the layout having a single button named button_example:

Android context menu example

Android context menu example

We then use registerForContextMenu in the onCreate of the activity to tell android that we want this view to create a menu when it is long pressed. This is not limited to buttons, this will work for other views too. You must register each view that you want to have associated with the context menu.

Button btn = (Button) findViewById(R.id.button_example);
registerForContextMenu(btn);

You then need to override the onCreateContextMenu method to create the menu:

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
	super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Context Menu");
		menu.add(0, v.getId(), 0, "Action 1");
		menu.add(0, v.getId(), 0, "Action 2");
	}
android context menu example

android context menu example

And override onContextItemSelected to preform the action when an option is selected from this menu:

    @Override
	public boolean onContextItemSelected(MenuItem item) {
       	if(item.getTitle()=="Action 1"){function1(item.getItemId());}
    	else if(item.getTitle()=="Action 2"){function2(item.getItemId());}
    	else {return false;}
	return true;
	}

function1 and function2 are just place-holders at the moment that toast a message when they are used. In the above example we are choosing between Action 1 and Action 2 which define which function will be run when an item is selected. We have passed the ID of the view through the context menu and into this function so we can tell what the user was pressing when the context menu was created.

calling a function after a context menu item was pressed

calling a function after a context menu item was pressed

Examples

If you create a gridview and give each item a unique ID then you can use this method to preform actions based on each item. This is the method I use for my soundboard applications to save the sounds to the SD card as a notification or ringtone:

counterstrike 1.6 soundboard context menu

counterstrike 1.6 soundboard context menu


Unreal Tournament soundboard context menu

Unreal Tournament soundboard context menu

Source

Below is the source code:

package com.contextmenu.test;

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

public class test extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button btn = (Button) findViewById(R.id.button_example);
        registerForContextMenu(btn);        
    }
    
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
	super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("Context Menu");
		menu.add(0, v.getId(), 0, "Action 1");
		menu.add(0, v.getId(), 0, "Action 2");
	}

    @Override
	public boolean onContextItemSelected(MenuItem item) {
       	if(item.getTitle()=="Action 1"){function1(item.getItemId());}
    	else if(item.getTitle()=="Action 2"){function2(item.getItemId());}
    	else {return false;}
	return true;
	}
    
    public void function1(int id){
    	Toast.makeText(this, "function 1 called", Toast.LENGTH_SHORT).show();
    }
    public void function2(int id){
    	Toast.makeText(this, "function 2 called", Toast.LENGTH_SHORT).show();
    }
}

70 Comments

  1. Roberto Silva

    bro ok, thank !

  2. Sander

    Nice tutorial, but in it is one of the most made Java programming mistakes ever, String comparison with ==
    YOu have to compare Strings with .equals

    corrected:

    @Override
    public boolean onContextItemSelected(MenuItem item) {
    if (item.getTitle().equals(“Action 1”)){
    function1(item.getItemId());
    } else if (item.getTitle().equals(“Action 2”)){
    function2(item.getItemId());
    } else {
    return false;
    }
    return true;
    }

  3. […] http://www.stealthcopter.com/blog/2010/04/android-context-menu-example-on-long-press-gridview/ Follow this example to make a longpress then just have the menu it pops up contain a text input which returns the value of the text input. […]

  4. Tarunjot Singh

    Thanks a lot for this code……….

    God bless you with peace and prosperity……..

  5. Mohamed

    thanks a lot. 🙂

    i’m appreciate your effort .. many thanks again.

  6. pawan

    very nice tutorial you can also check this one
    http://pavanhd.blogspot.in/2013/02/android-context-menu-example.html

  7. trt

    tdr

  8. pavan

    Very effective and detailed explainaion
    context menu

  9. Nikhil

    Thanks

  10. […] Android Context Menu on long press […]

  11. Dharmishtha

    it’s good but i have one error on this program

    error in one line
    which is line no. 19 plz solve this.

  12. Shehzad

    Nice tutorial:
    but i have problem that context menu is displayed when i long press the button…please tell me the solution for this

  13. Shehzad

    nice but i have a problem that context menu is displayed when i long press the button please do something

  14. kavitha

    Nice Tutorial

  15. Hiren

    Dharmisha Change the id of button to declared in a R.java file …. then it can be run successfully…. 🙂

  16. The Master World

    Contextual Action mode in android studio
    if you are beginner and do not know how create a contextual action mode in android then this lecture can help a lot
    http://themasterworld.com/working-with-contextual-action-mode-android-studio/

  17. […] have seen tutorials (link1 and link2) providing context menus for grid view items. These are shown on long press on the items. I am […]

  18. mehdi

    tanx a lot.

    but how can I get position gridview in context menu?!

  19. hot-hoodies.com

    Appear for a women’s sweatshirts and hoodies that are soft to the touch and feel lightweight to
    maintain you comfy without unneeded bulk.

Leave a Comment

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