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();
    }
}

74 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. follia del giorno

    I think this is among the most vital info for me.
    And i’m glad reading your article. But should remark on few general things, The website style is great, the articles is really nice :
    D. Good job, cheers

  20. CREDO SYSTEMZ

    Informative concepts of context menu in android..Android Training

  21. piano hoodies

    Hello, yes this post is actually nice and I have learned lot of things from it on the topic of blogging.

    thanks.

  22. accounting guys tee

    It aids not exclusive in enhancing the form perceptibility direct but also straight impacts the
    call memory measure. The Jordan Brazil Pack
    will drop June 21 for a suggested retail price of $500. over the net saree
    buying is one thing which has come going to be really favored as well as many females
    are looking at this.

  23. https://klout.com

    Will there be one thing known as cat mario unblocked? Reportedly, plenty of web sites tend not to
    provide absolutely free service to individuals to relax and play this game.
    In the feel, the game is simply not thoroughly available on the
    net and scarcely, of course rarely you can get some sites giving and free and complete
    accessibility video game. By the way, if you learn an individual or any, please
    do allow us to. We certainly have been interested in some cat mario unblocked
    program. At any rate, moving on to a different one feature about Cat Mario, we must be frank in this
    article all over again and declare that /~970525733406036903 (https://klout.com) no era limitations.
    You can participate in this game as well as the main purpose of this would be to like it if possible but while there is
    absolutely nothing known as cat mario unblocked, plenty of your enjoyment removal
    will hinge with in places you have fun with this game.
    The official site is where you can try it out but there might
    be some payment to be manufactured.

    Hello there there! This is just about the very best activity from Weebly and it’s definitely unblocked!
    Participate in Cat Mario at school, do the job or at home each day.
    Enjoy the fun!

    Cat Mario 2 , 3 Match Unblocked Syobon Motion is
    really a 2D Japanese system freeware indie computer
    game released in February 2007. This action match offers
    a distinct tackle one of many worldโ€™s most desired
    video gaming. Direct the white pet cat from the Mushroom Kingdom.

    Instead of Goombas and Koopas, you will be against
    an army of icky blobs.

    Aid a little Cat Mario defeat all obstacles!
    Within this unblocked activity for school, it is important to
    take control of your pet cat and make its way by means of
    all discrepant locations full of impediments.

    Get past they all, gather much more helpful products
    and check out your very best to beat all adversaries.
    All the best !!

Leave a Comment

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