tags:

views:

103

answers:

2

I have two activities that both contain an identical context menu built programmatically using menu.add(int, int, int, CharSequence). They both use onCreateContextMenu and onContextItemSelected.

The first Activity contains a ListView, when the user long presses on an item the context menu appears for that item. The second Activity (a detail screen for each item in Activity 1) contains a button, when the user presses the button the context menu appears.

I'd like to share the code that creates the context menu between these activities. The only thing these activities share is the context menu, so it seems like a bit of overkill to create a superclass (e.g., ActivityOne extends ContextMenuActivity) that defines onCreateContextMenu and onContextItemSelected methods.

Is there a better way of sharing these methods between activities?

+1  A: 

A context menu is probably either tied to the specific view or the context. You can define your menu in xml and inflate it into the Menu object in onCreateContextMenu.

Go down to "Define Menus in XML"

BrennaSoft
I've been avoiding xml for this particular context menu because the items in the menu change based on the item pressed (or detail page).
Richard
+1  A: 

extend an activity overriding the menu stuff, then extend this activity for your other activities. if you need to change the menu between activities override the menu stuff in you new activities and call super.

android dev guide explains it for options menu but should work for context menus and dialogs. http://developer.android.com/guide/topics/ui/menus.html

sugarynugs