How to create multiple context menus?

I have 1 activity, but I would like to have several context menus for different user interface components.

For example, I have a ListView that will respond 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 do I create another context menu for the onClick event for ImageView that I have?

+4
source share
3 answers

Actually this method consists in dynamically changing the options menu. To create multiple context menus, you must define them in your onCreateContextMenu method. As you can see, this method receives the View as parameter, which is the View you clicked on to display the menu. This way you save the method that you have for your ListView , and you add some conditions to distinguish your Views . Then you use these conditions to create the desired Context Menu .

Note. Context menus do not support icons, so if you need icons, images, or something similar, you will either have to use the options menu that you dynamically change, or create your own menu using a custom view, intent, and all that.

+10
source

You can use tags .

Before registering in the appropriate context menu, set the tag on 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 the current tag in the root directory:

 Integer contextMenuId = (Integer) rootView.getTag(R.id.TAG_CONTEXT_MENU_ID); if (CONTEXT_MENU_YOUR_ACTION.equals(contextMenuId)) { //custom your context menu } 

The same applies to the onContextItemSelected method.

+2
source
 @Override public boolean onPrepareOptionsMenu(Menu menu) { // TODO Auto-generated method stub return super.onPrepareOptionsMenu(menu); } 

You can check your conditions as part of this method. This will be launched before the menu becomes visible to the user.

-5
source

All Articles