This funcction should be called in onCreateOptionsMenu of Activity or Fragment to inflate a new menu.
@param menuId
162328
public void createMenu(int menuId){
        mToolbar.inflateMenu(menuId);
        mMenuDataChanged = true;
        if(mAppCompatDelegate == null)
            onPrepareMenu();
    }
76468
@Override
    public void onMenuStateChanged(@NonNull MenuState menuState) {
        if (menuState == MenuState.CLOSING && popupMenu != null) {
            popupMenu.dismiss();
        }
    }
1335450
public function add($menuId)
    {
        $this->loadModel('Menu.Menus');
        $this->loadModel('Content.Contents');
        $menu = $this->Menus->get($menuId);
        $link = $this->Menus->MenuLinks->newEntity();
        $link->set([
            'activation' => 'auto',
            'status' => 1,
            'menu_id' => $menuId
        ]);
        $this->Menus->MenuLinks->addBehavior('Tree', [
            'scope' => ['menu_id' => $menu->id]
        ]);

        if ($this->request->data()) {
            $link = $this->Menus->MenuLinks->patchEntity($link, $this->request->data, [
                'fieldList' => [
                    'parent_id',
                    'title',
                    'url',
                    'description',
                    'target',
                    'expanded',
                    'active',
                    'activation',
                    'status'
                ]
            ]);

            if ($this->Menus->MenuLinks->save($link)) {
                $this->Menus->MenuLinks->recover();
                $this->Flash->success(__d('menu', 'Link successfully created!'));

                if (!empty($this->request->data['action_add'])) {
                    $this->redirect(['plugin' => 'Menu', 'controller' => 'links', 'action' => 'add', $menuId]);
                } elseif (!empty($this->request->data['action_menu'])) {
                    $this->redirect(['plugin' => 'Menu', 'controller' => 'links', 'action' => 'menu', $menuId]);
                }
            } else {
                $this->Flash->danger(__d('menu', 'Link could not be saved, please check your information'));
            }
        }

        $contentLinks = [];
        $contents = $this->Contents
            ->find()
            ->select(['id', 'slug', 'content_type_slug', 'title'])
            ->all();
        foreach ($contents as $content) {
            $contentLinks[stripLanguagePrefix($content->get('url'))] = __d('menu', '{0} [{1}]', [
                $content->title,
                $content->content_type_slug
            ]);
        }

        $parentsTree = $this->Menus->MenuLinks
            ->find('treeList', ['spacer' => '--'])
            ->map(function ($link) {
                if (strpos($link, '-') !== false) {
                    $link = str_replace_last('-', '- ', $link);
                }

                return $link;
            });

        $this->title(__d('menu', 'Create New Link'));
        $this->set(compact('menu', 'link', 'contentLinks', 'parentsTree'));
        $this->Breadcrumb
            ->push('/admin/menu/manage')
            ->push(__d('menu', 'Editing menu "{0}"', $menu->title), ['plugin' => 'Menu', 'controller' => 'manage', 'action' => 'edit', $menuId])
            ->push(__d('menu', 'Links'), ['plugin' => 'Menu', 'controller' => 'links', 'action' => 'menu', $menuId])
            ->push(__d('menu', 'Add new link'), '#');
    }
516958
public static MenuItem createFromExistingWithId(MenuItem selected, int newId) {
        return visitWithResult(selected, new AbstractMenuItemVisitor<MenuItem>() {
            @Override
            public void visit(AnalogMenuItem item) {
                setResult(AnalogMenuItemBuilder.anAnalogMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }

            @Override
            public void visit(BooleanMenuItem item) {
                setResult(BooleanMenuItemBuilder.aBooleanMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }

            @Override
            public void visit(EnumMenuItem item) {
                setResult(EnumMenuItemBuilder.anEnumMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }

            @Override
            public void visit(SubMenuItem item) {
                setResult(SubMenuItemBuilder.aSubMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }

            @Override
            public void visit(TextMenuItem item) {
                setResult(TextMenuItemBuilder.aTextMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }

            @Override
            public void visit(RemoteMenuItem item) {
                setResult(RemoteMenuItemBuilder.aRemoteMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }

            @Override
            public void visit(FloatMenuItem item) {
                setResult(FloatMenuItemBuilder.aFloatMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }
            @Override
            public void visit(ActionMenuItem item) {
                setResult(ActionMenuItemBuilder.anActionMenuItemBuilder()
                        .withExisting(item)
                        .withId(newId)
                        .menuItem()
                );
            }
        }).orElse(null);
    }
148773
private void openMenu(){
		sleeper.sleepMini();

		if(!dialogUtils.waitForDialogToOpen(MINI_WAIT, false)) {
			try{
				sender.sendKeyCode(KeyEvent.KEYCODE_MENU);
				dialogUtils.waitForDialogToOpen(WAIT_TIME, true);
			}catch(SecurityException e){
				Assert.fail("Can not open the menu!");
			}
		}
	}
1175975
public void onClick(MenuItemClickEvent event) {
		if (editController.getInfoLabel() == null) {
			editController.showGeometricInfo();
		} else {
			editController.hideGeometricInfo();
		}
	}
961526
public function cloneMenu(int $menuId, int $siteId, string $name): Tree
    {
        $source = $this->menuStorage->load($menuId);
        $values = [
            'title'       => $source->getTitle(),
            'description' => $source->getDescription(),
            'site_id'     => $siteId,
        ];
        $target = $this->menuStorage->create($name, $values);

        return $this->cloneTreeIn($target->getId(), $this->buildTree($menuId));
    }
793457
public function setMenuId( $menuId )
    {
        $this->menuId = empty( $menuId ) ? null : (int) $menuId;

        if ( null !== $this->_menu &&
             $this->_menu->id != $this->menuId )
        {
            $this->_menu = null;
        }

        return $this;
    }
107137
@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        switchMenu = menu.add("Switch WMS Layer");
    }
292281
private void enableMenu(final JMenu menu) {
    menu.setEnabled(true);
    for (final Component c : menu.getMenuComponents()) {
      if (c instanceof JMenu) {
        enableMenu((JMenu) c);
      } else if (c instanceof JMenuItem) {
        ((JMenuItem) c).setEnabled(true);
      }
    }
  }
43108
public void setMenuView(int layoutResId) {
        mMenuContainer.removeAllViews();
        mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false);
        mMenuContainer.addView(mMenuView);
    }
78228
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }
802839
private void initUserMenu() {

        if (!m_user.isManaged()) {
            m_menu.addMenuEntry(
                CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_CHANGE_PASSWORD_BUTTON_0),
                null).addClickListener(new ClickListener() {

                    private static final long serialVersionUID = 1L;

                    public void buttonClick(ClickEvent event) {

                        m_context.start(
                            CmsVaadinUtils.getMessageText(org.opencms.ui.Messages.GUI_PWCHANGE_HEADER_0)
                                + m_user.getSimpleName(),
                            new CmsChangePasswordDialog(m_context));
                    }
                });
        }
        final CmsPreferencesDialogAction preferencesAction = new CmsPreferencesDialogAction();
        m_menu.addMenuEntry(preferencesAction.getTitle(A_CmsUI.get().getLocale()), null).addClickListener(
            new ClickListener() {

                private static final long serialVersionUID = 1L;

                public void buttonClick(ClickEvent event) {

                    preferencesAction.executeAction(m_context);
                }
            });
        if (!m_user.isManaged()) {
            m_menu.addMenuEntry(CmsVaadinUtils.getMessageText(Messages.GUI_USER_EDIT_0), null).addClickListener(
                new Button.ClickListener() {

                    private static final long serialVersionUID = 1L;

                    public void buttonClick(ClickEvent event) {

                        editUserData();
                    }
                });
        }
        m_menu.addMenuEntry(
            CmsVaadinUtils.getMessageText(org.opencms.workplace.explorer.Messages.GUI_EXPLORER_CONTEXT_LOGOUT_0),
            null).addClickListener(new Button.ClickListener() {

                private static final long serialVersionUID = 1L;

                public void buttonClick(ClickEvent event) {

                    logout();
                }
            });
    }
1077599
public static MenuItemTransitionBuilder transit(String id, @NonNull Toolbar toolbar) {
        return new MenuItemTransitionBuilder(id, toolbar);
    }
976352
public void clickOnActionBarHomeButton() {
		Activity activity = activityUtils.getCurrentActivity();
		MenuItem homeMenuItem = null;

		try {
			Class<?> cls = Class.forName("com.android.internal.view.menu.ActionMenuItem");
			Class<?> partypes[] = new Class[6];
			partypes[0] = Context.class;
			partypes[1] = Integer.TYPE;
			partypes[2] = Integer.TYPE;
			partypes[3] = Integer.TYPE;
			partypes[4] = Integer.TYPE;
			partypes[5] = CharSequence.class;
			Constructor<?> ct = cls.getConstructor(partypes);
			Object argList[] = new Object[6];
			argList[0] = activity;
			argList[1] = 0;
			argList[2] = android.R.id.home;
			argList[3] = 0;
			argList[4] = 0;
			argList[5] = "";
			homeMenuItem = (MenuItem) ct.newInstance(argList);
		} catch (Exception ex) {
			Log.d(LOG_TAG, "Can not find methods to invoke Home button!");
		}

		if (homeMenuItem != null) {
			try{
				activity.getWindow().getCallback().onMenuItemSelected(Window.FEATURE_OPTIONS_PANEL, homeMenuItem);
			}catch(Exception ignored) {}
		}
	}
343969
private void menuRedoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_menuRedoActionPerformed
    final TabTitle title = this.getFocusedTab();
    if (title != null) {
      this.menuRedo.setEnabled(title.getProvider().redo());
      this.menuUndo.setEnabled(title.getProvider().isUndo());
    }
  }
248979
private void createMenus(Collection<ActionRef> parents, Collection<ActionRef> actions)
    {
        for (final ActionRef action : actions)
        {
            final Featurable menu = createMenu(action);
            if (!action.getRefs().isEmpty())
            {
                generateSubMenu(actions, action, menu);
            }
            else if (action.hasCancel())
            {
                previous.put(action, parents);
                generateCancel(action, menu);
            }
        }
        for (final Featurable current : menus)
        {
            handler.add(current);
        }
    }