tags:

views:

176

answers:

3

Hi, I'm new to Android. I have a list of items and trying to associate single context menus to each list item. Have set setListAdapter and onListItemClick but when i click on any list item i get always 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?

Many thanks and happy xmas,

Stefano

+4  A: 

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().

CommonsWare
A: 

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

Jim Schubert
That sample, while good, does not show a context menu, per the posted question.
CommonsWare
Can it be adapted to create the context menu instead of LinearLayout? I could be wrong, or maybe I chose the wrong sample. I was looking through these last night and there seemed to be way more than are listed on the site.
Jim Schubert
A: 

Thanks a lot to both of you, Jim and Commonsware. You sorted my problem out.

Stefano

Stefano