I have 1 activity, but would like to have multiple context menu's for different UI components.
For example, I have a ListView which will react to:
@Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Selection Options");
menu.add(0, v.getId(), 0, "Remove");
}
How can I create another context menu for the onClick event for an ImageView I have?
Actually, this method is to change the option menu dynamically. To create several context menus, you have to define them in your method onCreateContextMenu
. As you can see, this method receives a View as parameter, which is the View you clicked on to make the menu appear. So you keep the method you have for your ListView
, and you add some conditions to differentiate your Views
. Then you use these conditions to create the wanted Context Menu
.
Note : Context Menus don't support icons, so if you want icons, images or something similar you will have to either use an option menu you dynamically change, or create a custom menu with a custom view, intents and everything.
You can make use of tags
.
Before registration to the relevant context menu, set a tag on your rootView
:
private static final Integer CONTEXT_MENU_YOUR_ACTION = 1; //indicator of the current context menu type
// register for your context menu
rootView.setTag(R.id.TAG_CONTEXT_MENU_ID, CONTEXT_MENU_YOUR_ACTION);
registerForContextMenu(rootView);
rootView.showContextMenu();
unregisterForContextMenu(rootView);
Then inside onCreateContextMenu
you can check for the current tag on your rootView:
Integer contextMenuId = (Integer) rootView.getTag(R.id.TAG_CONTEXT_MENU_ID);
if (CONTEXT_MENU_YOUR_ACTION.equals(contextMenuId)) {
//custom your context menu
}
The same check is relevant for the onContextItemSelected
method.
@Override
public boolean onPrepareOptionsMenu(Menu menu)
{
// TODO Auto-generated method stub
return super.onPrepareOptionsMenu(menu);
}
You can check your conditions within this method. This will get fired before the menu is visible to user.