Show a context menu for long-clicks in an Android ListView

Coming from a Windows and .NET background, I had some trouble understanding how to interact with the ListView control and context menu creation in Android. Context menus are supposed to be shown on your mobile device when you touch/click the screen and hold on for a longer time. So here is how to determine which item is long-clicked and how to show a context menu for it.

Source code for this blog post is available as a complete Eclipse project at (zip download link in upper right corner).

An Activity with an expanding ListView and a docked TextView

If you have an activity that will only contain a single ListView control, you can derive your activity from the ListActivity instead of Activity. However, I think I might like to show some extra info below my ListView so I chose to have a separate ListView object. My activity layout looks like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""

And I need the layout for items in the ListView (listitem.xml):

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

Note a nice trick that I’ve used to get the TextView to “dock” at the bottom with a definied height, and have the ListView automatically fill out the rest of the height. This kind of thinking is important since Android devices can have different resolutions. The trick is to set the layout_height to zero pixels and the layout_weight to one (default is zero). Not sure about the logic behind that, but it works!

In order to have something to put into my ListView, I created a few country names in a string array as a resource and I sort that array before adding it to the ListView with the ArrayAdapter object. (Check out source code link above for this content.)

public class ListViewDemoActivity extends Activity {
  private String[] Countries;

  public void onCreate(Bundle savedInstanceState) {
    Countries = getResources().getStringArray(R.array.countries);

    ListView list = (ListView)findViewById(;
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.listitem, Countries);

Creating a ContextMenu in Android

When the user long-clicks, the event onCreateContextMenu is fired for the control that the user is clicking. For me, that is the ListView control. But since I don’t want to write a custom ListView-derived class, I want to catch that event in my activity. There does not seem to be any bubbling going on. Events fired in a child control does not bubble up to the parent if they are unhandled.

But obviously, the api designers have thought of this since there is a special method for this situation. Call the registerForContextMenu in your activity for this! This will actually make sure your overridden methods for both onCreateContextMenu and onContextItemSelected is called for the ListView-events as we’ll see soon.

Next, we’ll provide the implementation of onCreateContextMenu. Here I want to ensure that the event comes from the ListView and if so, I want to determine on which item in the ListView the user long-clicked.

public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
  if (v.getId() {
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
    String[] menuItems = getResources().getStringArray(;
    for (int i = 0; i<menuItems.length; i++) {
      menu.add(Menu.NONE, i, i, menuItems[i]);

As you can see, the argument of type ContextMenuInfo can actually change depending on what type of control is sending the event. For ListViews, the class you need to type cast into is AdapterView.AdapterContextMenuInfo. From there I used the position, which in my case corresponds to the index into the string-array. From the array I retrieve the string for that particular item and use as title for the menu. Then you can of course add all the menu commands you like. For the demo, I defined another string array as a resource with the commands I want to add.

When creating the menu items with the add-call, I specify that I don’t want any grouping of the items (Menu.NONE) and that the order and id of the item is the same (i). The last argument to add is the text to display for the item.

Screen capture of the context menu with commands

Responding to selected MenuItem

If the user dismisses the context menu (for instance, by back button) you don’t need to do anything. But for catching the actual selection of one of the items, you need to override onContextItemSelected.

public boolean onContextItemSelected(MenuItem item) {
  AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
  int menuItemIndex = item.getItemId();
  String[] menuItems = getResources().getStringArray(;
  String menuItemName = menuItems[menuItemIndex];
  String listItemName = Countries[info.position];

  TextView text = (TextView)findViewById(;
  text.setText(String.format("Selected %s for item %s", menuItemName, listItemName));
  return true;

The MenuItem argument holds all information that you need. The ContextMenuInfo object that got sent to onCreateContextMenu is still there and still needs type casting. Or I guess you could have saved that info in the activity between the calls, but I didn’t.

The id of the menu item selected is the same as the index into the string array of menu item texts for me. Instead of just outputting the menu command name and the list item text in a TextView, you would most likely have a big switch statement on menuItemIndex.

This was my first blog post and code demo for the Android platform. I hope it won’t be the last! The goal is to build upon this demo and/or other demos in my investigations of the Android platform. Please let me know in the comments if you have even better methods or code patterns that solves problems like this.

103 Responses to “Show a context menu for long-clicks in an Android ListView”

  1. Rickard says:


  2. sumit asok says:

    great tutorial…simple and effective.

  3. sumit asok says:

    for me this
    android:layout_height=”0px” android:layout_weight=”1″
    thing is not working
    at first it sets itself to bottom,
    but when the list increases it goes down.
    This program has an automatically increasing list.
    if any answer pls mail me.

  4. Skydancer says:

    That’s what I was searching for the whole day long. Thanks!!

  5. piyush says:

    Nice… i must say..

    Thanks ….

  6. Anonymous says:

    […] Show a context menu for long-clicks in an Android ListView – Mike Plate […]

  7. Thank u for providing open Source for android application

  8. hjandrzej says:

    this is absolutely fantastic!!!!! life saver! needed exactly this situation for coursework!!


  9. BarMonger says:

    Great tutorial, thanks.
    The official API documentation is less than helpful but your guide is great 🙂

  10. Hey thanks, this is *useful* code.

    … Opposed to the similar Google sample code for a ListView which is horribly assembled, missing pieces, and includes a disclaimer that you “shouldn’t ever actually do it this way”. 🙂

  11. Reynold says:

    Thanks, the ListView with the docked View is exactly what I was trying to do and I made use of SetHeaderTitle as well.

  12. Weixi says:

    Thanks a bunch for the code to get which ListItem was selected! 😉 Great Guide!

  13. endenis says:

    Thanks, very useful tutorial!

  14. sohaib rahman says:

    Excellent and awesome!!!!! Really a helpful stuff!

  15. Thulasi says:

    nice and very helpful tutorial..

  16. umesh says:

    its nice tutorial

  17. Rohaan says:

    You sir, are a genius.
    Nice and simple. exactly what i needed.

  18. kevin says:

    hi mike,

    this was very useful, clear and to the point. thanks for posting it.

  19. Harsh says:

    Working and a very nice tutorial..!!
    appreciate the effort.

  20. Surendra says:

    public void onButtonClick(View v)
    Toast.makeText(this, “Button clicked!”, Toast.LENGTH_SHORT).show();

    why this Code not Work plz rply my mail

  21. Surendra says:

    Hello Sir
    My Android AVD Simulator have Some Unexped error said closed forcly why this problem occurs plz rply some solution

  22. Jason Hamm says:

    Could you please send me an explanation of the code

    if (v.getId()

    I keep looking at it but it still doesn’t make sense to me.

    • mikeplate says:

      No problem. I’m just making sure that the View that was longpressed, is the ListView that I want to show the context menu for. I haven’t tried it, but if I were to longpress on the TextView at the bottom (with the short explanation) and didn’t have this if statement, the context menu would show for that event too. The “v” in the example is the View that was longpressed.

  23. Michael says:

    Thanks a lot! Nice, simple and useful tutorial. Keep on doin’ it.

  24. r says:

    You sir, are a savior. Thank you for the registerForContextMenu!

  25. Dave says:

    Thanks would have been days getting there …

  26. Xoce says:


    simple but really good!

  27. timperthwa says:

    Excellent! works as advertised 🙂

  28. sweaty says:

    my footer text and sub menu are not shown. what should i do….
    i even copy d exect code bt still face this problem

  29. Jack Welch says:

    Thanks so much. This is crystal clear and a huge help for someone like me who decided to jump into android programming and learns best from example code.

  30. Ramya says:

    Thank you………….. it helps me alot……

  31. Maniac says:

    May God Bless Man!! You have just saved me hours end on of scouring the internet for this exact masterpiece of work….. Great work!

  32. Liviu says:

    This is perfect! Thank you!

  33. […] by: Like this:LikeBe the first to like this […]

  34. Naresh says:

    its tooo good. because its what i thought to find. i m trying this concept very long time. thankz

  35. You are quietly brilliant says:

    You are quietly brilliant!

  36. ridwan says:

    Thanks so Much… ^_^G

  37. FlacoX says:

    nice… solved my problem

  38. Arvind says:


  39. GiftedHorse says:

    It’s just wonderful that this code is clear, concise and actually working on my device, so big thumbs up to the author/creator of this page to share this code.

    One addition that would make this page even better (ahem, and help me personally with my task at hand) is to post the code to catch a single/short press on any of the list items.

    Does anyone have a working example?

  40. sarah says:

    that’s what i was searching for my project..
    it’s great,,but when i try this code is there some script is not working like this script “” and “R.array.countries”
    may i know why..?
    can you help me..

  41. mikeplate says:

    @sarah Yes, those two names refers to array resource files in xml-format with the sample menu commands and countries in the list. The general format of such a file look like this

  42. Umesh says:

    Great tutorial.
    Just i want to know how to set background for particular item in context menu.
    Thanks in advance.

  43. RajaReddy says:

    Nice tutorial………….

  44. jlengrand says:

    Thx man 😉
    Saved me some hours

  45. […] Show a context menu for long-clicks in an Android ListView […]

  46. Daniel Marjamäki says:

    Great article. Short and simple to read. And it has all the info I needed.

  47. Saggio says:

    Nice Work!

  48. Christopher says:

    Thanks for this tutorial i used it to understand how contextmenu work and implemented it into my code with several changes to code.

  49. alguem says:

    Great tutorial.

  50. Xaviera says:

    Really helpful to me. Great tutorial.
    Thank you!

  51. Kofi says:

    excellent tutorial. very simple and understanding. Thank you

  52. Amazingly good article. You need to give some thought to writing full-time.
    Quick question though, how do you combat spam comments?
    My website is flooded each minute and my plugin is not
    doing a great job of sifting the good from the bad. Any tips?

  53. BalaVishnu says:

    gr8 1…very useful for me

  54. […] @Override   public boolean onContextItemSelected(MenuItem item) {     switch (item.getItemId()) {       case DELETE_ID:         AdapterView.AdapterContextMenuInfo info=           (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();         delete(;         return(true);     }     return(super.onOptionsItemSelected(item));   } Thats all… hope it helps.. Some references: […]

  55. Thats Indeed very nice tutorial on android context menu
    you can also check the different kinds of menus in android and there purpose at
    Option Menu
    Context Menu
    Popup Menu

  56. akshay says:

    Great tutorial exactly what i was looking for.
    By the way, none of the images are displaying.

  57. Well explained, good work!

  58. eli says:

    great article ,Thanks a lot!

  59. tomaki says:

    thanks a lot!

  60. suraj says:

    how context menu consume the listview position.

  61. Quique says:

    Thank very much!!!

    Greetings from Spain. 🙂

  62. Palanivelraghul says:

    Hats off to you sir….
    Thanks for your answer

  63. Anonymous says:

    great..and simply done

  64. Thiago Bordignon says:

    excellent !!!!

  65. Juan says:

    Great post! Thank you for sharing this information!!!

  66. Gabriela says:

    Excelente Tutorial.

    El tutorial mas claro y conciso que consegui.


  67. Gj says:

    Very nice!! Thank you so much!!

  68. samer says:

    Great Tutorial
    Thank you very much

  69. Benjamin says:

    I am a newbie so I might be missing some basic stuff here.
    Unclear to me where is the connection between the two layouts?
    listitem.xml and main.xml

    I think was able to under what is should do but unclear to me where does the list gets each item?
    I am unable to run this as a project, Android studio doesn’t recognize it.


  70. Paras says:

    how i can add functionality of share option in contextview after long pressing the list view in an android app ?

  71. omid says:

    thanks so much
    it was helpful

  72. Mick says:

    Count one more helped Android programmer. TQVM.

  73. Francois says:

    Still relevant 🙂

    Thank you!

  74. Gopika Vysakh says:

    Helpful lecture. .Thanks

  75. You’re a real deep thinker. Thanks for sharing.

  76. That’s way the bestest answer so far!

  77. Bethany, it sounds like you’ve had a very successful year. I know I’m glad I found your site. Downloaded a couple freebies and yesterday purchased the cable purse pattern.Wishing even greater success this year!

  78. softescope says:

    Good job,,,thanks ….

  79. fantastic work, patrick! i LOVE the willie scotts, marions and the sallah! i know a lucky 12 year old who’s going to get the first box when it hits the stores! (maybe he’ll share with his 30+ old dad.):)

  80. these are beautiful. i have an obsession with beads girl. i can't make anything to save my life but i use to buy it for the girls all the time – i think more for me than them so they could make me stuff. of course our beads were the tiny cheap ones. i'm dying in envy here. and hello? i love your vintage stuff.

  81. The real question is, "how to motivate kids and parents"? Schools and parents are reluctant to "hold a student back a grade". The problem starts with having a grade system. Classes should be more like college classes, one class might be prerequisite to the next, but age should not be the selection criteria. Even playing on the baseball team should be based on ability not age and those failing in class should spend extra time in the classroom while others enjoy extracuricular activities.

  82. WRT Kidd: Note that I included the size/role caveat–Kidd is unusually big and strong, even for a modern PG, and he certainly was when he started out. That allows for easier cross-matching. But, as you suggest, the point holds: Kidd, Nash and Stockton are all HOFers.

  83. Please Lord strenthen & encourage Jim & also Ian who have suffered nervous breakdowns in the last 12 months. Also strengthen Tim in mind & body as he recovers from hepatitus C.

  84. Professor conheco directa e pessoalmente o senhor Filipe, presidente do GDB. Dirigia/dirige em Inhamizua, uma escola/centro orfanato filiada a uma uma organizacao cristo Missionario da qual fiz parte em tempos idos. Diz-se por ca que quis se apostar nas igrejas e seu povo para se fazer face a populariedade de Deviz Simango.

  85. YESSSS I love a good flying squirt! And that needle with the pearl on the end of it – an earring?- looks like the perfect cyst popping tool! Stick it in, roll it around a little bit….it sure did the trick on this little sucker!

  86. Until I found this I thought I’d have to spend the day inside.

  87. http://www./ says:

    My tenant is living in my property for over 3-months now. He has paid rent on time so far but he is a very irritating tenant. Today we discovered that the bathroom drain is blocked because of a block caused by either cement or something of that sorts. We are slapped with a huge bill by plumber. Can we ask our tenant to pay this? If he denies, can we get an eviction?

  88. My husband is working on his MBA in an Executive program at a prestigious university and the most successful people (financially as well as title and authority) in the group all have a few traits in common. They are all thin, attractive, of average ability and super skilled at faking or actually having interest in other people. Oddly enough, the smartest people seem to have less responsibility, especially management duties.

  89. ça doit être un vrai bordel au niveau des connections ! la tt se fais en AirPlay ! rageux de la marque Apple … vous me faites tous rire . mais restez avec vos Pc surpuissants à savoir qui aura la plus grosse pour jouer en réseaux comme des geek que vous êtes et laisser les produit Apple aux autres. bande de naze

  90. inverted cross is not, I repeat is not a Occultic symbol. It is the symbol of St. Peter. Peter was crucified upside down after refusing to die in the same manner as Christ stating he was not worthy of such a death. Since that time the Inverted cross has been a deeply reverent and spiritual symbol. At least for anyone who has ever read a Real History book. I bebelive there are powers that want to control the human population. But we need direction, not incoherence and fantasy.

  91. http://www./ says:

    Pretty nice post. I simply stumbled upon your weblog and wished to mention that I have truly enjoyed browsing your blog posts. In any case I will be subscribing to your feed and I am hoping you write again soon!

  92. http://www./ says:

    Tanto John McCain como Barack Obama, si tenemos en cuenta únicamente sus programas, encontrarían acomodo en el Pp sin demasiados problemas, quizás con la pena de muerte se sentirían incómodos porque oficialmente los de Génova son contrarios a su práctica.

Leave a Reply

Twitter: @mikeplate