Example usage for android.view MenuItem setIcon

List of usage examples for android.view MenuItem setIcon

Introduction

In this page you can find the example usage for android.view MenuItem setIcon.

Prototype

public MenuItem setIcon(@DrawableRes int iconRes);

Source Link

Document

Change the icon associated with this item.

Usage

From source file:de.tum.in.tumcampus.auxiliary.calendar.DayView.java

public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
    MenuItem item;

    // If the trackball is held down, then the context menu pops up and
    // we never get onKeyUp() for the long-press. So check for it here
    // and change the selection to the long-press state.
    /*if (mSelectionMode != SELECTION_LONGPRESS) {
    mSelectionMode = SELECTION_LONGPRESS;
    invalidate();/*w  ww  .  j  a va 2 s  . c  o m*/
    }*/

    final long startMillis = getSelectedTimeInMillis();
    int flags = DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_CAP_NOON_MIDNIGHT | DateUtils.FORMAT_SHOW_WEEKDAY;
    final String title = DayUtils.formatDateRange(mContext, startMillis, startMillis, flags);
    menu.setHeaderTitle(title);

    int numSelectedEvents = mSelectedEvents.size();
    if (mNumDays == 1) {
        // Day view.

        // If there is a selected event, then allow it to be viewed and
        // edited.
        if (numSelectedEvents >= 1) {
            item = menu.add(0, MENU_EVENT_VIEW, 0, "View event");
            item.setOnMenuItemClickListener(mContextMenuHandler);
            item.setIcon(android.R.drawable.ic_menu_info_details);
        }
    } else {
        // Week view.

        // If there is a selected event, then allow it to be viewed and
        // edited.
        if (numSelectedEvents >= 1) {
            item = menu.add(0, MENU_EVENT_VIEW, 0, "View event");
            item.setOnMenuItemClickListener(mContextMenuHandler);
            item.setIcon(android.R.drawable.ic_menu_info_details);
        }

        item = menu.add(0, MENU_DAY, 0, "Show day");
        item.setOnMenuItemClickListener(mContextMenuHandler);
        item.setIcon(android.R.drawable.ic_menu_day);
        item.setAlphabeticShortcut('d');
    }
}

From source file:com.cerema.cloud2.ui.activity.FileDisplayActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    boolean retval = true;
    switch (item.getItemId()) {
    case R.id.action_sync_account: {
        startSynchronization();//from  w  w w  .  j  av a  2  s  .  c om
        break;
    }
    case android.R.id.home: {
        FileFragment second = getSecondFragment();
        OCFile currentDir = getCurrentDir();
        if (mDrawerLayout.isDrawerOpen(GravityCompat.START)) {
            mDrawerLayout.closeDrawer(GravityCompat.START);
        } else if ((currentDir != null && currentDir.getParentId() != 0)
                || (second != null && second.getFile() != null)) {
            onBackPressed();

        } else {
            mDrawerLayout.openDrawer(GravityCompat.START);
        }
        break;
    }
    case R.id.action_sort: {
        SharedPreferences appPreferences = PreferenceManager.getDefaultSharedPreferences(this);

        // Read sorting order, default to sort by name ascending
        Integer sortOrder = appPreferences.getInt("sortOrder", FileStorageUtils.SORT_NAME);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.actionbar_sort_title).setSingleChoiceItems(R.array.actionbar_sortby,
                sortOrder, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                        case 0:
                            sortByName(true);
                            break;
                        case 1:
                            sortByDate(false);
                            break;
                        }

                        dialog.dismiss();
                    }
                });
        builder.create().show();
        break;
    }
    case R.id.action_switch_view: {
        if (isGridView()) {
            item.setTitle(getString(R.string.action_switch_grid_view));
            item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_module));
            getListOfFilesFragment().setListAsPreferred();
        } else {
            item.setTitle(getApplicationContext().getString(R.string.action_switch_list_view));
            item.setIcon(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_view_list));
            getListOfFilesFragment().setGridAsPreferred();
        }
        return true;
    }
    default:
        retval = super.onOptionsItemSelected(item);
    }
    return retval;
}

From source file:org.openintents.shopping.ui.ShoppingActivity.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    boolean drawerOpen = mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mDrawerListsView);
    boolean holoSearch = PreferenceActivity.getUsingHoloSearchFromPrefs(this);
    // TODO: supposed to hide content-related actions when the drawer is open.

    // TODO: Add item-specific menu items (see NotesList.java example)
    // like edit, strike-through, delete.

    // Add menu option for auto adding items from string array in intent
    // extra if they exist
    if (mExtraItems == null) {
        menu.removeItem(MENU_INSERT_FROM_EXTRAS);
    }/*  w ww. jav a  2s . c  o  m*/

    // Selected list:
    long listId = getSelectedListId();

    // set menu title for change mode
    MenuItem menuItem = menu.findItem(MENU_PICK_ITEMS);

    if (mItemsView.mMode == MODE_ADD_ITEMS) {
        menuItem.setTitle(R.string.menu_start_shopping);
        menuItem.setIcon(android.R.drawable.ic_menu_myplaces);
    } else {
        menu.findItem(MENU_PICK_ITEMS).setTitle(R.string.menu_pick_items);
        menuItem.setIcon(android.R.drawable.ic_menu_add);
    }

    menuItem = menu.findItem(MENU_SEARCH_ADD);
    if (menuItem != null) {
        menuItem.setVisible(holoSearch && !drawerOpen);
        if (!holoSearch) {
            mAddPanel.setVisibility(View.VISIBLE);
        }

        View searchView = menuItem.getActionView();
        int searchImgId = getResources().getIdentifier("android:id/search_button", null, null);
        View imageView = searchView.findViewById(searchImgId);
        if (imageView instanceof ImageView) {
            ((ImageView) imageView).setImageResource(android.R.drawable.ic_menu_add);
        }

    }

    menuItem = menu.findItem(MENU_SYNC_WEAR);
    if (menuItem != null) {
        menuItem.setVisible(mItemsView.isWearSupportAvailable());
    }

    menuItem = menu.findItem(MENU_MARK_ALL_ITEMS).setVisible(mItemsView.mNumUnchecked > 0);
    menuItem = menu.findItem(MENU_UNMARK_ALL_ITEMS).setVisible(mItemsView.mNumChecked > 0);

    menuItem = menu.findItem(MENU_CLEAN_UP_LIST).setEnabled(mItemsView.mNumChecked > 0).setVisible(!drawerOpen);

    // Delete list is possible, if we have more than one list:
    // AND
    // the current list is not the default list (listId == 0) - issue #105
    // TODO: Later, the default list should be user-selectable,
    // and not deletable.

    // TODO ???
    /*
     * menu.setItemShown(MENU_DELETE_LIST, mCursorListFilter.count() > 1 &&
     * listId != 1); // 1 is hardcoded number of default first list.
     */

    // The following code is put from onCreateOptionsMenu to
    // onPrepareOptionsMenu,
    // because the URI of the shopping list can change if the user switches
    // to another list.
    // Generate any additional actions that can be performed on the
    // overall list. This allows other applications to extend
    // our menu with their own actions.
    Intent intent = new Intent(null, getIntent().getData());
    intent.addCategory(Intent.CATEGORY_ALTERNATIVE);
    // menu.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
    // new ComponentName(this, NoteEditor.class), null, intent, 0, null);

    // Workaround to add icons:
    MenuIntentOptionsWithIcons menu2 = new MenuIntentOptionsWithIcons(this, menu);
    menu2.addIntentOptions(Menu.CATEGORY_ALTERNATIVE, 0, 0,
            new ComponentName(this, org.openintents.shopping.ShoppingActivity.class), null, intent, 0, null);

    return true;
}

From source file:org.videolan.vlc.gui.MyFragment.java

/**
 * Handle onClick form menu buttons//from   www  .  jav  a 2s .c  om
 */
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // Current fragment loaded
    Fragment current = getSupportFragmentManager().findFragmentById(R.id.fragment_placeholder);

    // Handle item selection
    switch (item.getItemId()) {
    case R.id.ml_menu_sortby_name:
    case R.id.ml_menu_sortby_length:
    case R.id.ml_menu_sortby_date:
        if (current == null)
            break;
        if (current instanceof ISortable) {
            int sortBy = VideoListAdapter.SORT_BY_TITLE;
            if (item.getItemId() == R.id.ml_menu_sortby_length)
                sortBy = VideoListAdapter.SORT_BY_LENGTH;
            else if (item.getItemId() == R.id.ml_menu_sortby_date)
                sortBy = VideoListAdapter.SORT_BY_DATE;
            ((ISortable) current).sortBy(sortBy);
            supportInvalidateOptionsMenu();
        }
        break;
    case R.id.ml_menu_equalizer:
        showSecondaryFragment(SecondaryActivity.EQUALIZER);
        break;
    case R.id.ml_menu_preferences:
        //               showSecondaryFragment(PreferencesActivity.EQUALIZER);
        startActivity(new Intent(this, PreferencesActivity.class));

        break;
    // Refresh
    case R.id.ml_menu_refresh:
        if (!mMediaLibrary.isWorking()) {
            if (current != null && current instanceof IRefreshable)
                ((IRefreshable) current).refresh();
            else
                mMediaLibrary.scanMediaItems(true);
        }
        break;
    // Restore last playlist
    case R.id.ml_menu_last_playlist:
        if (current instanceof AudioBrowserFragment) {
            Intent i = new Intent(PlaybackService.ACTION_REMOTE_LAST_PLAYLIST);
            sendBroadcast(i);
        } else if (current instanceof VideoGridFragment) {
            final Uri uri = Uri.parse(mSettings.getString(PreferencesActivity.VIDEO_LAST, null));
            if (uri != null)
                VideoPlayerActivity.start(this, uri);
        }
        break;
    case android.R.id.home:
        // Slide down the audio player.
        if (slideDownAudioPlayer())
            break;
        //                /* Toggle the sidebar */
        //                if (mDrawerToggle.onOptionsItemSelected(item)) {
        //                    return true;
        //                }
        break;
    case R.id.ml_menu_clean:
        if (getFragment(mCurrentFragment) instanceof MRLPanelFragment)
            ((MRLPanelFragment) getFragment(mCurrentFragment)).clearHistory();
        break;
    case R.id.ml_menu_save:
        if (current == null)
            break;
        ((NetworkBrowserFragment) current).toggleFavorite();
        item.setIcon(R.drawable.ic_menu_bookmark_w);
        break;
    }
    //        mDrawerLayout.closeDrawer(mListView);
    return super.onOptionsItemSelected(item);
}

From source file:org.getlantern.firetweet.util.Utils.java

public static void addIntentToMenuForExtension(final Context context, final Menu menu, final int groupId,
        final String action, final String parelableKey, final String parelableJSONKey,
        final FiretweetParcelable parcelable) {
    if (context == null || menu == null || action == null || parelableKey == null || parcelable == null)
        return;/*w w w .j av a2  s  .co m*/
    final PackageManager pm = context.getPackageManager();
    final Resources res = context.getResources();
    final float density = res.getDisplayMetrics().density;
    final int padding = Math.round(density * 4);
    final Intent queryIntent = new Intent(action);
    queryIntent.setExtrasClassLoader(context.getClassLoader());
    final List<ResolveInfo> activities = pm.queryIntentActivities(queryIntent, PackageManager.GET_META_DATA);
    for (final ResolveInfo info : activities) {
        final Intent intent = new Intent(queryIntent);
        if (isExtensionUseJSON(info)) {
            intent.putExtra(parelableJSONKey, JSONSerializer.toJSONObjectString(parcelable));
        } else {
            intent.putExtra(parelableKey, parcelable);
        }
        intent.setClassName(info.activityInfo.packageName, info.activityInfo.name);
        final MenuItem item = menu.add(groupId, Menu.NONE, Menu.NONE, info.loadLabel(pm));
        item.setIntent(intent);
        final Drawable metaDataDrawable = getMetadataDrawable(pm, info.activityInfo,
                METADATA_KEY_EXTENSION_ICON);
        final int actionIconColor = ThemeUtils.getThemeForegroundColor(context);
        if (metaDataDrawable != null) {
            metaDataDrawable.mutate();
            metaDataDrawable.setColorFilter(actionIconColor, Mode.SRC_ATOP);
            item.setIcon(metaDataDrawable);
        } else {
            final Drawable icon = info.loadIcon(pm);
            final int iw = icon.getIntrinsicWidth(), ih = icon.getIntrinsicHeight();
            if (iw > 0 && ih > 0) {
                final Drawable iconWithPadding = new PaddingDrawable(icon, padding);
                iconWithPadding.setBounds(0, 0, iw, ih);
                item.setIcon(iconWithPadding);
            } else {
                item.setIcon(icon);
            }
        }

    }
}

From source file:com.ichi2.anki2.DeckPicker.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuItem item;

    if (mFragmented) {
        UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_SYNC, Menu.NONE, R.string.sync_title,
                R.drawable.ic_menu_refresh);

        UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_ADD_NOTE, Menu.NONE, R.string.add,
                R.drawable.ic_menu_add);

        int icon;
        SharedPreferences preferences = AnkiDroidApp.getSharedPrefs(this);
        if (preferences.getBoolean("invertedColors", false)) {
            icon = R.drawable.ic_menu_night_checked;
        } else {/*from  ww  w. j a  v a  2  s.  c  o  m*/
            icon = R.drawable.ic_menu_night;
        }
        UIUtils.addMenuItemInActionBar(menu, Menu.NONE, StudyOptionsActivity.MENU_NIGHT, Menu.NONE,
                R.string.night_mode, icon);

        UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_STATISTICS, Menu.NONE, R.string.statistics_menu,
                R.drawable.ic_menu_statistics);

        UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_CARDBROWSER, Menu.NONE, R.string.menu_cardbrowser,
                R.drawable.ic_menu_cardbrowser);
    }
    UIUtils.addMenuItemInActionBar(menu, Menu.NONE, MENU_HELP, Menu.NONE, R.string.help_title,
            R.drawable.ic_menu_help);

    item = menu.add(Menu.NONE, MENU_PREFERENCES, Menu.NONE, R.string.menu_preferences);
    item.setIcon(R.drawable.ic_menu_preferences);
    item = menu.add(Menu.NONE, MENU_ADD_SHARED_DECK, Menu.NONE, R.string.menu_get_shared_decks);
    item.setIcon(R.drawable.ic_menu_download);
    item = menu.add(Menu.NONE, MENU_CREATE_DECK, Menu.NONE, R.string.new_deck);
    item.setIcon(R.drawable.ic_menu_add);
    item = menu.add(Menu.NONE, MENU_CREATE_DYNAMIC_DECK, Menu.NONE, R.string.new_dynamic_deck);
    item.setIcon(R.drawable.ic_menu_add);
    item = menu.add(Menu.NONE, MENU_IMPORT, Menu.NONE, R.string.menu_import);
    item.setIcon(R.drawable.ic_menu_download);
    UIUtils.addMenuItem(menu, Menu.NONE, CHECK_DATABASE, Menu.NONE, R.string.check_db,
            R.drawable.ic_menu_search);
    item = menu.add(Menu.NONE, StudyOptionsActivity.MENU_ROTATE, Menu.NONE, R.string.menu_rotate);
    item.setIcon(R.drawable.ic_menu_always_landscape_portrait);
    item = menu.add(Menu.NONE, MENU_FEEDBACK, Menu.NONE, R.string.studyoptions_feedback);
    item.setIcon(R.drawable.ic_menu_send);
    item = menu.add(Menu.NONE, MENU_ABOUT, Menu.NONE, R.string.menu_about);
    item.setIcon(R.drawable.ic_menu_info_details);
    item = menu.add(Menu.NONE, MENU_REUPGRADE, Menu.NONE, R.string.restart_upgrade_process);
    item.setIcon(R.drawable.ic_menu_preferences);

    return true;
}

From source file:org.mozilla.gecko.BrowserApp.java

/**
 * Add the provided item to the provided menu, which should be
 * the root (mMenu)./*from   w w  w  .ja  v a 2 s.  c  om*/
 */
private void addAddonMenuItemToMenu(final Menu menu, final MenuItemInfo info) {
    info.added = true;

    final Menu destination;
    if (info.parent == 0) {
        destination = menu;
    } else if (info.parent == GECKO_TOOLS_MENU) {
        // The tools menu only exists in our -v11 resources.
        if (Versions.feature11Plus) {
            final MenuItem tools = menu.findItem(R.id.tools);
            destination = tools != null ? tools.getSubMenu() : menu;
        } else {
            destination = menu;
        }
    } else {
        final MenuItem parent = menu.findItem(info.parent);
        if (parent == null) {
            return;
        }

        Menu parentMenu = findParentMenu(menu, parent);

        if (!parent.hasSubMenu()) {
            parentMenu.removeItem(parent.getItemId());
            destination = parentMenu.addSubMenu(Menu.NONE, parent.getItemId(), Menu.NONE, parent.getTitle());
            if (parent.getIcon() != null) {
                ((SubMenu) destination).getItem().setIcon(parent.getIcon());
            }
        } else {
            destination = parent.getSubMenu();
        }
    }

    final MenuItem item = destination.add(Menu.NONE, info.id, Menu.NONE, info.label);

    item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("Menu:Clicked",
                    Integer.toString(info.id - ADDON_MENU_OFFSET)));
            return true;
        }
    });

    if (info.icon == null) {
        item.setIcon(R.drawable.ic_menu_addons_filler);
    } else {
        final int id = info.id;
        BitmapUtils.getDrawable(this, info.icon, new BitmapUtils.BitmapLoader() {
            @Override
            public void onBitmapFound(Drawable d) {
                // TODO: why do we re-find the item?
                final MenuItem item = destination.findItem(id);
                if (item == null) {
                    return;
                }
                if (d == null) {
                    item.setIcon(R.drawable.ic_menu_addons_filler);
                    return;
                }
                item.setIcon(d);
            }
        });
    }

    item.setCheckable(info.checkable);
    item.setChecked(info.checked);
    item.setEnabled(info.enabled);
    item.setVisible(info.visible);
}

From source file:com.nttec.everychan.ui.presentation.BoardFragment.java

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    MenuItem itemAddPost = menu.add(Menu.NONE, R.id.menu_add_post, 101, resources
            .getString(pageType == TYPE_POSTSLIST ? R.string.menu_add_post : R.string.menu_add_thread));
    MenuItem itemUpdate = menu.add(Menu.NONE, R.id.menu_update, 102, resources.getString(
            tabModel.type != TabModel.TYPE_LOCAL ? R.string.menu_update : R.string.menu_from_internet));
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        itemAddPost.setIcon(ThemeUtils.getActionbarIcon(activity.getTheme(), resources, R.attr.actionAddPost));
        itemUpdate.setIcon(ThemeUtils.getActionbarIcon(activity.getTheme(), resources, R.attr.actionRefresh));
        CompatibilityImpl.setShowAsActionIfRoom(itemAddPost);
        CompatibilityImpl.setShowAsActionIfRoom(itemUpdate);
    } else {//from   w w w  .j a va 2  s. co  m
        itemAddPost.setIcon(R.drawable.ic_menu_edit);
        itemUpdate.setIcon(R.drawable.ic_menu_refresh);
    }
    menu.add(Menu.NONE, R.id.menu_catalog, 103, resources.getString(R.string.menu_catalog))
            .setIcon(R.drawable.ic_menu_list);
    menu.add(Menu.NONE, R.id.menu_search, 104, resources.getString(R.string.menu_search))
            .setIcon(android.R.drawable.ic_menu_search);
    menu.add(Menu.NONE, R.id.menu_save_page, 105, resources.getString(R.string.menu_save_page))
            .setIcon(android.R.drawable.ic_menu_save);
    menu.add(Menu.NONE, R.id.menu_board_gallery, 106, resources.getString(R.string.menu_board_gallery))
            .setIcon(android.R.drawable.ic_menu_slideshow);
    menu.add(Menu.NONE, R.id.menu_quickaccess_add, 107, resources.getString(R.string.menu_quickaccess_add))
            .setIcon(R.drawable.ic_menu_add_bookmark);
    this.menu = menu;
    updateMenu();
}

From source file:org.mozilla.gecko.BrowserApp.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Tab tab = null;//www .  jav  a2  s .  com
    Intent intent = null;

    final int itemId = item.getItemId();

    // Track the menu action. We don't know much about the context, but we can use this to determine
    // the frequency of use for various actions.
    Telemetry.sendUIEvent(TelemetryContract.Event.ACTION, TelemetryContract.Method.MENU,
            getResources().getResourceEntryName(itemId));

    mBrowserToolbar.cancelEdit();

    if (itemId == R.id.bookmark) {
        tab = Tabs.getInstance().getSelectedTab();
        if (tab != null) {
            if (item.isChecked()) {
                Telemetry.sendUIEvent(TelemetryContract.Event.UNSAVE, TelemetryContract.Method.MENU,
                        "bookmark");
                tab.removeBookmark();
                item.setIcon(resolveBookmarkIconID(false));
                item.setTitle(resolveBookmarkTitleID(false));
            } else {
                Telemetry.sendUIEvent(TelemetryContract.Event.SAVE, TelemetryContract.Method.MENU, "bookmark");
                tab.addBookmark();
                item.setIcon(resolveBookmarkIconID(true));
                item.setTitle(resolveBookmarkTitleID(true));
            }
        }
        return true;
    }

    if (itemId == R.id.reading_list) {
        tab = Tabs.getInstance().getSelectedTab();
        if (tab != null) {
            if (item.isChecked()) {
                Telemetry.sendUIEvent(TelemetryContract.Event.UNSAVE, TelemetryContract.Method.MENU,
                        "reading_list");
                tab.removeFromReadingList();
                item.setIcon(resolveReadingListIconID(false));
                item.setTitle(resolveReadingListTitleID(false));
            } else {
                Telemetry.sendUIEvent(TelemetryContract.Event.SAVE, TelemetryContract.Method.MENU,
                        "reading_list");
                tab.addToReadingList();
                item.setIcon(resolveReadingListIconID(true));
                item.setTitle(resolveReadingListTitleID(true));
            }
        }
        return true;
    }

    if (itemId == R.id.share) {
        shareCurrentUrl();
        return true;
    }

    if (itemId == R.id.reload) {
        tab = Tabs.getInstance().getSelectedTab();
        if (tab != null)
            tab.doReload();
        return true;
    }

    if (itemId == R.id.back) {
        tab = Tabs.getInstance().getSelectedTab();
        if (tab != null)
            tab.doBack();
        return true;
    }

    if (itemId == R.id.forward) {
        tab = Tabs.getInstance().getSelectedTab();
        if (tab != null)
            tab.doForward();
        return true;
    }

    if (itemId == R.id.save_as_pdf) {
        GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("SaveAs:PDF", null));
        return true;
    }

    if (itemId == R.id.settings) {
        intent = new Intent(this, GeckoPreferences.class);

        // We want to know when the Settings activity returns, because
        // we might need to redisplay based on a locale change.
        startActivityForResult(intent, ACTIVITY_REQUEST_PREFERENCES);
        return true;
    }

    if (itemId == R.id.help) {
        final String VERSION = AppConstants.MOZ_APP_VERSION;
        final String OS = AppConstants.OS_TARGET;
        final String LOCALE = Locales.getLanguageTag(Locale.getDefault());

        final String URL = getResources().getString(R.string.help_link, VERSION, OS, LOCALE);
        Tabs.getInstance().loadUrlInTab(URL);
        return true;
    }

    if (itemId == R.id.addons) {
        Tabs.getInstance().loadUrlInTab(AboutPages.ADDONS);
        return true;
    }

    if (itemId == R.id.logins) {
        Tabs.getInstance().loadUrlInTab(AboutPages.LOGINS);
        return true;
    }

    if (itemId == R.id.downloads) {
        Tabs.getInstance().loadUrlInTab(AboutPages.DOWNLOADS);
        return true;
    }

    if (itemId == R.id.char_encoding) {
        GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("CharEncoding:Get", null));
        return true;
    }

    if (itemId == R.id.find_in_page) {
        mFindInPageBar.show();
        return true;
    }

    if (itemId == R.id.desktop_mode) {
        Tab selectedTab = Tabs.getInstance().getSelectedTab();
        if (selectedTab == null)
            return true;
        JSONObject args = new JSONObject();
        try {
            args.put("desktopMode", !item.isChecked());
            args.put("tabId", selectedTab.getId());
        } catch (JSONException e) {
            Log.e(LOGTAG, "error building json arguments", e);
        }
        GeckoAppShell.sendEventToGecko(GeckoEvent.createBroadcastEvent("DesktopMode:Change", args.toString()));
        return true;
    }

    if (itemId == R.id.new_tab) {
        addTab();
        return true;
    }

    if (itemId == R.id.new_private_tab) {
        addPrivateTab();
        return true;
    }

    if (itemId == R.id.new_guest_session) {
        showGuestModeDialog(GuestModeDialog.ENTERING);
        return true;
    }

    if (itemId == R.id.exit_guest_session) {
        showGuestModeDialog(GuestModeDialog.LEAVING);
        return true;
    }

    // We have a few menu items that can also be in the context menu. If
    // we have not already handled the item, give the context menu handler
    // a chance.
    if (onContextItemSelected(item)) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

From source file:com.esri.squadleader.view.SquadLeaderActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.add_layer:
        //Present Add Layer from Web dialog
        if (null == addLayerDialogFragment) {
            addLayerDialogFragment = new AddLayerDialogFragment();
            addLayerDialogFragment.setAddLayerFromFileRequestCode(ADD_LAYER_FROM_FILE);
        }/*from  ww  w  . j av  a  2 s  .  com*/
        addLayerDialogFragment.show(getFragmentManager(), getString(R.string.add_layer_fragment_tag));
        return true;
    case R.id.add_feature:
        // Present Add Feature dialog
        if (null == addFeatureDialogFragment) {
            addFeatureDialogFragment = new AddFeatureDialogFragment();
        }
        addFeatureDialogFragment.show(getFragmentManager(), getString(R.string.add_feature_fragment_tag));
        return true;
    case R.id.clear_messages:
        //Present Clear Messages dialog
        if (null == clearMessagesDialogFragment) {
            clearMessagesDialogFragment = new ClearMessagesDialogFragment();
        }
        clearMessagesDialogFragment.show(getFragmentManager(), getString(R.string.clear_messages_fragment_tag));
        return true;
    case R.id.go_to_mgrs:
        //Present Go to MGRS dialog
        if (null == goToMgrsDialogFragment) {
            goToMgrsDialogFragment = new GoToMgrsDialogFragment();
        }
        goToMgrsDialogFragment.show(getFragmentManager(), getString(R.string.go_to_mgrs_fragment_tag));
        return true;
    case R.id.set_location_mode:
        //Present Set Location Mode dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.set_location_mode).setNegativeButton(R.string.cancel, null)
                .setSingleChoiceItems(
                        new String[] { getString(R.string.option_location_service),
                                getString(R.string.option_simulation_builtin),
                                getString(R.string.option_simulation_file) },
                        mapController.getLocationController().getMode() == LocationMode.LOCATION_SERVICE ? 0
                                : null == mapController.getLocationController().getGpxFile() ? 1 : 2,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                clearDisplayStrings();
                                try {
                                    if (2 == which) {
                                        //Present file chooser
                                        Intent getContentIntent = FileUtils.createGetContentIntent();
                                        Intent intent = Intent.createChooser(getContentIntent, "Select a file");
                                        startActivityForResult(intent, REQUEST_CHOOSER);
                                    } else {
                                        mapController.getLocationController().setGpxFile(null, true);
                                        mapController.getLocationController()
                                                .setMode(0 == which ? LocationMode.LOCATION_SERVICE
                                                        : LocationMode.SIMULATOR, true);
                                        mapController.getLocationController().start();
                                    }
                                } catch (Exception e) {
                                    Log.d(TAG, "Couldn't set location mode", e);
                                } finally {
                                    dialog.dismiss();
                                }
                            }

                        });
        AlertDialog dialog = builder.create();
        dialog.show();
        return true;
    case R.id.settings:
        Intent intent = new Intent(this, SettingsActivity.class);
        startActivityForResult(intent, SETTINGS_ACTIVITY);
        return true;
    case R.id.toggle_labels:
        item.setChecked(!item.isChecked());
        item.setIcon(item.isChecked() ? R.drawable.ic_action_labels : R.drawable.ic_action_labels_off);
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        String key = getString(R.string.pref_labels);
        prefs.edit().putBoolean(key, item.isChecked()).commit();
        if (null != mil2525cController) {
            mil2525cController.setShowLabels(item.isChecked());
        }
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}