android - list items open context menus

1.1k views Asked by At

I'm new to Android. I have a list of items and trying to associate single context menus to each list item. I have set setListAdapter and onListItemClick but when I click on any list item I always get the same context menu.

Ideally, list item A should trigger menu A when cliccked and list item B should get menu B. Can't figure out how to do it. Could anybody help me find an example code I could use to learn how to do it?

2

There are 2 answers

0
CommonsWare On

I don't have any example code that shows the technique -- my best example is something I did for a consulting client.

However, let me point you to this sample project that uses context menus and use it as a basis for this explanation.

You need to return the customized menu in onCreateContextMenu(). If you always return the same menu here, you will always see the same menu. To determine which menu to display, you will need to know which list item was long-tapped. In the case of a context menu for a ListView, you can cast the ContextMenu.ContextMenuInfo supplied to onCreateContextMenu() to be an AdapterView.AdapterContextMenuInfo. That object can tell you the position and _ID of the item in the list that was long-tapped, so you can choose the proper menu.

In the sample code linked to above, I do that cast in onContextItemSelected(), so I can know which item the user is deleting. However, the same cast works in onCreateContextMenu().

3
Jim Schubert On

The Android team recently released a number of new samples. I believe what you're trying to do has an excellent example here.