How can I create multiple context menus?

久未见 提交于 2019-12-05 16:12:57

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!