Reputation: 2718
In my plugin, I have a pop up menu with menu item 'X' and I want to add submenu to this menu item
and the number and labels of menu items in the submenu and their action will change.
I think I can';t do this from plugin.xml, so how to do this programatically?
Upvotes: 0
Views: 3253
Reputation: 1023
In your plugin.xml, under org.eclipse.ui.menus, add a menuContribution that refers to the id of your "root" menu, i.e. the menu that you want to have your submenus attached to (in this case, menu:myDynamicMenuRoot):
<menuContribution
allPopups="true"
class="com.myCode.menus.MyDynamicMenuContributions"
locationURI="menu:myDynamicMenuRoot">
</menuContribution>
Note that allPopups="true" ensures that your submenus will be added to any menu with the id myDynamicMenuRoot that you add anywhere in your application.
Finally, create a class extending ExtensionContributionFactory, whose job it will be to create your dynamic submenu items. Here I add items based on commands I have defined in my plugin.xml:
public class MyDynamicMenuContributions extends ExtensionContributionFactory {
private static final ImageDescriptor GREEN_STAR = Plugin.getImageDescriptor("icons/green_star.png");
@Override
public void createContributionItems(IServiceLocator serviceLocator, IContributionRoot additions) {
// build a couple of command-based contribution parameters
CommandContributionItemParameter pAA = new CommandContributionItemParameter(
serviceLocator,
"Submenu_CommandAA",
"my.package.command.myCommandAA",
SWT.PUSH);
pAA.icon = GREEN_STAR;
pAA.label = "Command AA";
CommandContributionItemParameter pBB = new CommandContributionItemParameter(
serviceLocator,
"Submenu_CommandBB",
"my.package.command.myCommandBB",
SWT.PUSH);
pBB.icon = GREEN_STAR;
pBB.label = "Command BB";
// create actual contribution items and add them to the given additions reference
CommandContributionItem itemAA = new CommandContributionItem(pAA);
itemAA.setVisible(true);
additions.addContributionItem(itemAA, null);
CommandContributionItem itemBB = new CommandContributionItem(pBB);
itemBB.setVisible(true);
additions.addContributionItem(itemBB, null);
}
}
Upvotes: 2