Example usage for android.view MenuItem setTitle

List of usage examples for android.view MenuItem setTitle

Introduction

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

Prototype


public MenuItem setTitle(@StringRes int title);

Source Link

Document

Change the title associated with this item.

Usage

From source file:org.kontalk.ui.AbstractComposeFragment.java

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    MenuItem deleteMenu = menu.findItem(R.id.menu_delete);
    MenuItem retryMenu = menu.findItem(R.id.menu_retry);
    MenuItem shareMenu = menu.findItem(R.id.menu_share);
    MenuItem copyTextMenu = menu.findItem(R.id.menu_copy_text);
    MenuItem detailsMenu = menu.findItem(R.id.menu_details);
    MenuItem openMenu = menu.findItem(R.id.menu_open);
    MenuItem dlMenu = menu.findItem(R.id.menu_download);
    MenuItem cancelDlMenu = menu.findItem(R.id.menu_cancel_download);

    // initial status
    deleteMenu.setVisible(true);//  w  w w.  java 2  s.co m
    retryMenu.setVisible(false);
    shareMenu.setVisible(false);
    copyTextMenu.setVisible(false);
    detailsMenu.setVisible(false);
    openMenu.setVisible(false);
    dlMenu.setVisible(false);
    cancelDlMenu.setVisible(false);

    boolean singleItem = (mCheckedItemCount == 1);
    if (singleItem) {
        CompositeMessage msg = getCheckedItem();

        // group command can't be deleted or have details
        if (msg.hasComponent(GroupCommandComponent.class)) {
            deleteMenu.setVisible(false);
        } else {
            // message waiting for user review or not delivered
            if (msg.getStatus() == Messages.STATUS_PENDING || msg.getStatus() == Messages.STATUS_NOTDELIVERED) {
                retryMenu.setVisible(true);
            }

            // some commands can be used only on unencrypted messages
            if (!msg.isEncrypted()) {
                AttachmentComponent attachment = msg.getComponent(AttachmentComponent.class);
                TextComponent text = msg.getComponent(TextComponent.class);

                // sharing media messages has no purpose if media file hasn't been
                // retrieved yet
                if (text != null || attachment == null || attachment.getLocalUri() != null)
                    shareMenu.setVisible(true);

                // non-empty text: copy text to clipboard
                if (text != null && !TextUtils.isEmpty(text.getContent()))
                    copyTextMenu.setVisible(true);

                if (attachment != null) {

                    // message has a local uri - add open file entry
                    if (attachment.getLocalUri() != null) {
                        int resId;
                        if (attachment instanceof ImageComponent)
                            resId = R.string.view_image;
                        else if (attachment instanceof AudioComponent)
                            resId = R.string.open_audio;
                        else
                            resId = R.string.open_file;

                        openMenu.setTitle(resId);
                        openMenu.setVisible(true);
                    }

                    // message has a fetch url - add download control entry
                    if (msg.getDirection() == Messages.DIRECTION_IN && attachment.getFetchUrl() != null) {
                        if (!DownloadService.isQueued(attachment.getFetchUrl())) {
                            int string;
                            // already fetched
                            if (attachment.getLocalUri() != null)
                                string = R.string.download_again;
                            else
                                string = R.string.download_file;

                            dlMenu.setTitle(string);
                            dlMenu.setVisible(true);
                        } else {
                            cancelDlMenu.setVisible(true);
                        }
                    }
                }
            }

            detailsMenu.setVisible(true);
        }
    }
    return true;
}

From source file:com.segma.trim.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (isMenuLocked)
        return super.onOptionsItemSelected(item);
    ipv.setClickable(false);/*from w  ww.j  a v a2  s.  c  o  m*/
    switch (STATE) {
    case STATE_NO_IMAGE_IMPORTED:
        switch (item.getItemId()) {
        case R.id.online_gallery:
            goOnlineGallery();
            return super.onOptionsItemSelected(item);
        case R.id.premium:
            goPremium();
            return super.onOptionsItemSelected(item);
        case R.id.take_a_photo:
            photoFromCamera();
            return super.onOptionsItemSelected(item);
        case R.id.import_from_gallery:
            importFromGallery();
            return super.onOptionsItemSelected(item);
        case R.id.save_file:
            showWarning(WARNING_NO_IMAGE_IMPORTED);
            return super.onOptionsItemSelected(item);
        case R.id.show_mesh:
            showWarning(WARNING_NO_IMAGE_IMPORTED);
            return super.onOptionsItemSelected(item);
        case R.id.save_location:
            if (LICENSE == LICENSE_TRIAL) {
                Toast.makeText(getApplicationContext(), WARNING_PREMIUM_FEATURE_SAVE_IMAGE, Toast.LENGTH_SHORT)
                        .show();
                return super.onOptionsItemSelected(item);
            }
            showSaveLocation();
            return super.onOptionsItemSelected(item);
        case R.id.meshColor:
            showWarning(WARNING_NO_IMAGE_IMPORTED);
            return super.onOptionsItemSelected(item);
        case R.id.share:
            showWarning(WARNING_NO_IMAGE_IMPORTED);
            return super.onOptionsItemSelected(item);
        case R.id.about:
            showAbout();
            return super.onOptionsItemSelected(item);
        //TODO: 11-4-2016 FIX: Hiding Navigation Bar scheme dispose, exit button not required
        /*
        case R.id.exit:
            exit();
            return super.onOptionsItemSelected(item);
            */
        default:
            return super.onOptionsItemSelected(item);
        }
    case STATE_PROCESSING_IMAGE:
        switch (item.getItemId()) {
        case R.id.online_gallery:
            goOnlineGallery();
            return super.onOptionsItemSelected(item);
        case R.id.premium:
            goPremium();
            return super.onOptionsItemSelected(item);
        case R.id.take_a_photo:
            photoFromCamera();
            return super.onOptionsItemSelected(item);
        case R.id.import_from_gallery:
            importFromGallery();
            return super.onOptionsItemSelected(item);
        case R.id.save_file:
            if (LICENSE == LICENSE_TRIAL) {
                Toast.makeText(getApplicationContext(), WARNING_PREMIUM_FEATURE_SAVE_IMAGE, Toast.LENGTH_SHORT)
                        .show();
                return super.onOptionsItemSelected(item);
            }
            requestProcessedPhoto();
            return super.onOptionsItemSelected(item);
        case R.id.show_mesh:
            if (!ipv.SHOW_MESH) {
                item.setTitle(R.string.hide_mesh);
                ipv.showMesh(true);
                PREF_MESH_VALUE = true;
                preferenceEditor.putBoolean(PREF_MESH, PREF_MESH_VALUE);
                preferenceEditor.commit();
            } else {
                item.setTitle(R.string.show_mesh);
                ipv.showMesh(false);
                PREF_MESH_VALUE = false;
                preferenceEditor.putBoolean(PREF_MESH, PREF_MESH_VALUE);
                preferenceEditor.commit();
            }
            return super.onOptionsItemSelected(item);
        case R.id.meshColor:
            showColorPickerDialog();
            return super.onOptionsItemSelected(item);
        case R.id.save_location:
            if (LICENSE == LICENSE_TRIAL) {
                Toast.makeText(getApplicationContext(), WARNING_PREMIUM_FEATURE_SAVE_IMAGE, Toast.LENGTH_SHORT)
                        .show();
                return super.onOptionsItemSelected(item);
            }
            showSaveLocation();
            return super.onOptionsItemSelected(item);
        case R.id.share:
            /*
            if (LICENSE == LICENSE_TRIAL) {
                Toast.makeText(getApplicationContext(), WARNING_PREMIUM_FEATURE_SHARE_IMAGE, Toast.LENGTH_SHORT).show();
                return super.onOptionsItemSelected(item);
            }
            */
            share();
            return super.onOptionsItemSelected(item);
        case R.id.about:
            showAbout();
            return super.onOptionsItemSelected(item);
        //TODO: 11-4-2016 FIX: Hiding Navigation Bar scheme dispose, exit button not required
        /*
        case R.id.exit:
            exit();
            return super.onOptionsItemSelected(item);
            */
        default:
            return super.onOptionsItemSelected(item);
        }
    }
    ipv.setClickable(true);
    return super.onOptionsItemSelected(item);
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    Tab tab = null;/*from ww w.j ava  2s . c  om*/
    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:org.kontalk.ui.ComposeMessageFragment.java

@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
    MenuItem retryMenu = menu.findItem(R.id.menu_retry);
    MenuItem shareMenu = menu.findItem(R.id.menu_share);
    MenuItem copyTextMenu = menu.findItem(R.id.menu_copy_text);
    MenuItem detailsMenu = menu.findItem(R.id.menu_details);
    MenuItem openMenu = menu.findItem(R.id.menu_open);
    MenuItem dlMenu = menu.findItem(R.id.menu_download);
    MenuItem cancelDlMenu = menu.findItem(R.id.menu_cancel_download);
    MenuItem decryptMenu = menu.findItem(R.id.menu_decrypt);

    // initial status
    retryMenu.setVisible(false);//from w w  w . j  a  va 2s.c  om
    shareMenu.setVisible(false);
    copyTextMenu.setVisible(false);
    detailsMenu.setVisible(false);
    openMenu.setVisible(false);
    dlMenu.setVisible(false);
    cancelDlMenu.setVisible(false);
    decryptMenu.setVisible(false);

    boolean singleItem = (mCheckedItemCount == 1);
    if (singleItem) {
        CompositeMessage msg = getCheckedItem();

        // message waiting for user review or not delivered
        if (msg.getStatus() == Messages.STATUS_PENDING || msg.getStatus() == Messages.STATUS_NOTDELIVERED) {
            retryMenu.setVisible(true);
        }

        // some commands can be used only on unencrypted messages
        if (!msg.isEncrypted()) {
            AttachmentComponent attachment = (AttachmentComponent) msg.getComponent(AttachmentComponent.class);
            TextComponent text = (TextComponent) msg.getComponent(TextComponent.class);

            // sharing media messages has no purpose if media file hasn't been
            // retrieved yet
            if (text != null || attachment == null || attachment.getLocalUri() != null)
                shareMenu.setVisible(true);

            // non-empty text: copy text to clipboard
            if (text != null && !TextUtils.isEmpty(text.getContent()))
                copyTextMenu.setVisible(true);

            if (attachment != null) {

                // message has a local uri - add open file entry
                if (attachment.getLocalUri() != null) {
                    int resId;
                    if (attachment instanceof ImageComponent)
                        resId = R.string.view_image;
                    else if (attachment instanceof AudioComponent)
                        resId = R.string.open_audio;
                    else
                        resId = R.string.open_file;

                    openMenu.setTitle(resId);
                    openMenu.setVisible(true);
                }

                // message has a fetch url - add download control entry
                if (msg.getDirection() == Messages.DIRECTION_IN && attachment.getFetchUrl() != null) {
                    if (!DownloadService.isQueued(attachment.getFetchUrl())) {
                        int string;
                        // already fetched
                        if (attachment.getLocalUri() != null)
                            string = R.string.download_again;
                        else
                            string = R.string.download_file;

                        dlMenu.setTitle(string);
                        dlMenu.setVisible(true);
                    } else {
                        cancelDlMenu.setVisible(true);
                    }
                }

            }

        }

        else {

            decryptMenu.setVisible(true);

        }

        detailsMenu.setVisible(true);
    }
    return true;
}

From source file:com.if3games.chessonline.DroidFish.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem item = menu.findItem(R.id.item_file_menu);
    item.setTitle(boardGestures ? R.string.option_file : R.string.tools_menu);
    if (isSinglePlayer)
        return true;
    else/*www  .  j a  v  a 2  s .  c  o  m*/
        return false;
}

From source file:org.uoyabause.android.YabauseHandler.java

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    switch (id) {
    /*// w ww.  j  a  va2 s .co m
    case R.id.save_screen:{
        DateFormat dateFormat = new SimpleDateFormat("_yyyy_MM_dd_HH_mm_ss");
        Date date = new Date();
            
        String screen_shot_save_path = YabauseStorage.getStorage().getScreenshotPath()
                + YabauseRunnable.getCurrentGameCode() +
                dateFormat.format(date) + ".png";
            
        if (YabauseRunnable.screenshot(screen_shot_save_path) != 0) {
            break;
        }
            
        waiting_reault = true;
        Intent shareIntent = new Intent();
        shareIntent.setAction(Intent.ACTION_SEND);
        ContentResolver cr = getContentResolver();
        ContentValues cv = new ContentValues();
        cv.put(MediaStore.Images.Media.TITLE, YabauseRunnable.getCurrentGameCode());
        cv.put(MediaStore.Images.Media.DISPLAY_NAME, YabauseRunnable.getCurrentGameCode());
        cv.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
        cv.put(MediaStore.Images.Media.MIME_TYPE, "image/png");
        cv.put(MediaStore.Images.Media.DATA, screen_shot_save_path);
        Uri uri = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, cv);
        shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
        shareIntent.setType("image/png");
        startActivityForResult(Intent.createChooser(shareIntent, "share screenshot to"), 0x01);
    }
    break;
    */
    case R.id.reset:
        YabauseRunnable.reset();
        break;
    case R.id.report:
        startReport();
        break;
    case R.id.save_state: {
        String save_path = YabauseStorage.getStorage().getStateSavePath();
        String current_gamecode = YabauseRunnable.getCurrentGameCode();
        File save_root = new File(YabauseStorage.getStorage().getStateSavePath(), current_gamecode);
        if (!save_root.exists())
            save_root.mkdir();

        String save_filename = YabauseRunnable.savestate(save_path + current_gamecode);
        if (save_filename != "") {
            int point = save_filename.lastIndexOf(".");
            if (point != -1) {
                save_filename = save_filename.substring(0, point);
            }
            String screen_shot_save_path = save_filename + ".png";
            if (YabauseRunnable.screenshot(screen_shot_save_path) != 0) {
                Snackbar.make(this.mDrawerLayout, "Failed to save the current state", Snackbar.LENGTH_SHORT)
                        .show();
            } else {
                Snackbar.make(this.mDrawerLayout, "Current state is saved as " + save_filename,
                        Snackbar.LENGTH_LONG).show();
            }
        } else {
            Snackbar.make(this.mDrawerLayout, "Failed to save the current state", Snackbar.LENGTH_SHORT).show();
        }

        StateListFragment.checkMaxFileCount(save_path + current_gamecode);

    }
        break;
    case R.id.load_state: {
        //String save_path = YabauseStorage.getStorage().getStateSavePath();
        //YabauseRunnable.loadstate(save_path);
        String basepath;
        String save_path = YabauseStorage.getStorage().getStateSavePath();
        String current_gamecode = YabauseRunnable.getCurrentGameCode();
        basepath = save_path + current_gamecode;
        waiting_reault = true;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        StateListFragment fragment = new StateListFragment();
        fragment.setBasePath(basepath);
        transaction.replace(R.id.ext_fragment, fragment, StateListFragment.TAG);
        transaction.show(fragment);
        transaction.commit();
    }
        break;
    case R.id.menu_item_backup: {
        waiting_reault = true;
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        TabBackupFragment fragment = TabBackupFragment.newInstance("hoge", "hoge");
        //fragment.setBasePath(basepath);
        transaction.replace(R.id.ext_fragment, fragment, TabBackupFragment.TAG);
        transaction.show(fragment);
        transaction.commit();
    }
        break;
    case R.id.button_open_cd: {
        if (tray_state == 0) {
            YabauseRunnable.openTray();
            item.setTitle(getString(R.string.close_cd_tray));
            tray_state = 1;
        } else {
            item.setTitle(getString(R.string.open_cd_tray));
            tray_state = 0;
            File file = new File(gamepath);
            String path = file.getParent();
            FileDialog fd = new FileDialog(Yabause.this, path);
            fd.addFileListener(Yabause.this);
            fd.showDialog();
        }
    }
        break;
    case R.id.pad_mode: {
        YabausePad padv = (YabausePad) findViewById(R.id.yabause_pad);
        boolean mode = false;
        if (item.isChecked()) {
            item.setChecked(false);
            Yabause.this.padm.setAnalogMode(PadManager.MODE_HAT);
            YabauseRunnable.switch_padmode(PadManager.MODE_HAT);
            padv.setPadMode(PadManager.MODE_HAT);
            mode = false;
        } else {
            item.setChecked(true);
            Yabause.this.padm.setAnalogMode(PadManager.MODE_ANALOG);
            YabauseRunnable.switch_padmode(PadManager.MODE_ANALOG);
            padv.setPadMode(PadManager.MODE_ANALOG);
            mode = true;
        }
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(Yabause.this);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean("pref_analog_pad", mode);
        editor.apply();
        Yabause.this.showBottomMenu();
    }
        break;
    case R.id.menu_item_cheat: {
        waiting_reault = true;
        CheatEditDialogStandalone newFragment = new CheatEditDialogStandalone();
        newFragment.setGameCode(YabauseRunnable.getCurrentGameCode(), this.cheat_codes);
        newFragment.show(getFragmentManager(), "Cheat");
    }
        break;
    case R.id.exit: {
        YabauseRunnable.deinit();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {

        }
        //android.os.Process.killProcess(android.os.Process.myPid());
        finish();
        android.os.Process.killProcess(android.os.Process.myPid());
    }
        break;
    }
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

From source file:com.bernard.beaconportal.activities.activity.MessageList.java

/**
 * Hide menu items not appropriate for the current context.
 * /*from www  . j  a v a2 s  .c o m*/
 * <p>
 * <strong>Note:</strong> Please adjust the comments in
 * {@code res/menu/message_list_option.xml} if you change the visibility of
 * a menu item in this method.
 * </p>
 * 
 * @param mMenu2
 *            The {@link Menu} instance that should be modified. May be
 *            {@code null}; in that case the method does nothing and
 *            immediately returns.
 */
private void configureMenu(android.view.Menu mMenu2) {
    if (mMenu2 == null) {
        return;
    }

    // Set visibility of account/folder settings menu items
    if (mMessageListFragment == null) {
        mMenu2.findItem(R.id.account_settings).setVisible(false);
        mMenu2.findItem(R.id.folder_settings).setVisible(false);
    } else {
        mMenu2.findItem(R.id.account_settings).setVisible(mMessageListFragment.isSingleAccountMode());
        mMenu2.findItem(R.id.folder_settings).setVisible(mMessageListFragment.isSingleFolderMode());
    }

    /*
     * Set visibility of menu items related to the message view
     */

    if (mDisplayMode == DisplayMode.MESSAGE_LIST || mMessageViewFragment == null
            || !mMessageViewFragment.isInitialized()) {
        mMenu2.findItem(R.id.next_message).setVisible(false);
        mMenu2.findItem(R.id.previous_message).setVisible(false);
        mMenu2.findItem(R.id.single_message_options).setVisible(false);
        mMenu2.findItem(R.id.delete).setVisible(false);
        mMenu2.findItem(R.id.composeList).setVisible(false);
        mMenu2.findItem(R.id.composeView).setVisible(false);
        mMenu2.findItem(R.id.archive).setVisible(false);
        mMenu2.findItem(R.id.move).setVisible(false);
        mMenu2.findItem(R.id.copy).setVisible(false);
        mMenu2.findItem(R.id.spam).setVisible(false);
        mMenu2.findItem(R.id.refile).setVisible(false);
        mMenu2.findItem(R.id.toggle_unread).setVisible(false);
        mMenu2.findItem(R.id.select_text).setVisible(false);
        mMenu2.findItem(R.id.toggle_message_view_theme).setVisible(false);
        mMenu2.findItem(R.id.show_headers).setVisible(false);
        mMenu2.findItem(R.id.hide_headers).setVisible(false);

        final int splitBarId = getResources().getIdentifier("split_action_bar", "id", "android");
        final View splitActionBar = findViewById(splitBarId);

        SharedPreferences sharedpref = getSharedPreferences("actionbar_color", Context.MODE_PRIVATE);

        if (!sharedpref.contains("actionbar_color")) {

            if (splitActionBar != null) {

                splitActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#4285f4")));

            }

        } else {

            actionbar_colors = sharedpref.getString("actionbar_color", null);

            if (splitActionBar != null) {

                splitActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(actionbar_colors)));
            }

        }

    } else {
        // hide prev/next buttons in split mode
        if (mDisplayMode != DisplayMode.MESSAGE_VIEW) {
            mMenu2.findItem(R.id.next_message).setVisible(false);
            mMenu2.findItem(R.id.previous_message).setVisible(false);
        } else {
            MessageReference ref = mMessageViewFragment.getMessageReference();
            boolean initialized = (mMessageListFragment != null && mMessageListFragment.isLoadFinished());
            boolean canDoPrev = (initialized && !mMessageListFragment.isFirst(ref));
            boolean canDoNext = (initialized && !mMessageListFragment.isLast(ref));

            MenuItem prev = mMenu2.findItem(R.id.previous_message);
            prev.setEnabled(canDoPrev);
            // prev.getIcon().setAlpha(canDoPrev ? 255 : 127);

            // MenuItem next = menu.findItem(R.id.next_message);
            // next.setEnabled(canDoNext);
            // next.getIcon().setAlpha(canDoNext ? 255 : 127);

            final int splitBarId = getResources().getIdentifier("split_action_bar", "id", "android");
            final View splitActionBar = findViewById(splitBarId);

            if (splitActionBar != null) {

                splitActionBar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#ffffff")));
            }

        }

        MenuItem toggleTheme = mMenu2.findItem(R.id.toggle_message_view_theme);
        if (K9.useFixedMessageViewTheme()) {
            toggleTheme.setVisible(false);
        } else {
            // Set title of menu item to switch to dark/light theme
            if (K9.getK9MessageViewTheme() == K9.Theme.DARK) {
                toggleTheme.setTitle(R.string.message_view_theme_action_light);
            } else {
                toggleTheme.setTitle(R.string.message_view_theme_action_dark);
            }
            toggleTheme.setVisible(true);
        }

        // Set title of menu item to toggle the read state of the currently
        // displayed message
        if (mMessageViewFragment.isMessageRead()) {
            mMenu2.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_unread_action);
        } else {
            mMenu2.findItem(R.id.toggle_unread).setTitle(R.string.mark_as_read_action);
        }

        // Jellybean has built-in long press selection support
        mMenu2.findItem(R.id.select_text).setVisible(Build.VERSION.SDK_INT < 16);

        mMenu2.findItem(R.id.delete).setVisible(K9.isMessageViewDeleteActionVisible());

        /*
         * Set visibility of copy, move, archive, spam in action bar and
         * refile submenu
         */
        if (mMessageViewFragment.isCopyCapable()) {
            mMenu2.findItem(R.id.copy).setVisible(K9.isMessageViewCopyActionVisible());
            mMenu2.findItem(R.id.refile_copy).setVisible(true);
        } else {
            mMenu2.findItem(R.id.copy).setVisible(false);
            mMenu2.findItem(R.id.refile_copy).setVisible(false);
        }

        if (mMessageViewFragment.isMoveCapable()) {
            boolean canMessageBeArchived = mMessageViewFragment.canMessageBeArchived();
            boolean canMessageBeMovedToSpam = mMessageViewFragment.canMessageBeMovedToSpam();

            mMenu2.findItem(R.id.move).setVisible(K9.isMessageViewMoveActionVisible());
            mMenu2.findItem(R.id.archive)
                    .setVisible(canMessageBeArchived && K9.isMessageViewArchiveActionVisible());
            mMenu2.findItem(R.id.spam)
                    .setVisible(canMessageBeMovedToSpam && K9.isMessageViewSpamActionVisible());

            mMenu2.findItem(R.id.refile_move).setVisible(true);
            mMenu2.findItem(R.id.refile_archive).setVisible(canMessageBeArchived);
            mMenu2.findItem(R.id.refile_spam).setVisible(canMessageBeMovedToSpam);
        } else {
            mMenu2.findItem(R.id.move).setVisible(false);
            mMenu2.findItem(R.id.archive).setVisible(false);
            mMenu2.findItem(R.id.spam).setVisible(false);

            mMenu2.findItem(R.id.refile).setVisible(false);
        }

        if (mMessageViewFragment.allHeadersVisible()) {
            mMenu2.findItem(R.id.show_headers).setVisible(false);
        } else {
            mMenu2.findItem(R.id.hide_headers).setVisible(false);
        }
    }

    /*
     * Set visibility of menu items related to the message list
     */

    // Hide both search menu items by default and enable one when
    // appropriate
    mMenu2.findItem(R.id.search).setVisible(false);
    mMenu2.findItem(R.id.search_remote).setVisible(false);

    if (mDisplayMode == DisplayMode.MESSAGE_VIEW || mMessageListFragment == null
            || !mMessageListFragment.isInitialized()) {
        mMenu2.findItem(R.id.check_mail).setVisible(false);
        mMenu2.findItem(R.id.set_sort).setVisible(false);
        mMenu2.findItem(R.id.select_all).setVisible(false);
        mMenu2.findItem(R.id.send_messages).setVisible(false);
        mMenu2.findItem(R.id.expunge).setVisible(false);
        mMenu2.findItem(R.id.mark_all_as_read).setVisible(false);
        mMenu2.findItem(R.id.show_folder_list).setVisible(false);
    } else {
        mMenu2.findItem(R.id.set_sort).setVisible(true);
        mMenu2.findItem(R.id.select_all).setVisible(true);
        mMenu2.findItem(R.id.composeList).setVisible(true);
        mMenu2.findItem(R.id.mark_all_as_read).setVisible(mMessageListFragment.isMarkAllAsReadSupported());

        if (!mMessageListFragment.isSingleAccountMode()) {
            mMenu2.findItem(R.id.expunge).setVisible(false);
            mMenu2.findItem(R.id.send_messages).setVisible(false);
            mMenu2.findItem(R.id.show_folder_list).setVisible(false);
        } else {
            mMenu2.findItem(R.id.send_messages).setVisible(mMessageListFragment.isOutbox());
            mMenu2.findItem(R.id.expunge).setVisible(
                    mMessageListFragment.isRemoteFolder() && mMessageListFragment.isAccountExpungeCapable());
            mMenu2.findItem(R.id.show_folder_list).setVisible(true);
        }

        mMenu2.findItem(R.id.check_mail).setVisible(mMessageListFragment.isCheckMailSupported());

        // If this is an explicit local search, show the option to search on
        // the server
        if (!mMessageListFragment.isRemoteSearch() && mMessageListFragment.isRemoteSearchAllowed()) {
            mMenu2.findItem(R.id.search_remote).setVisible(true);
        } else if (!mMessageListFragment.isManualSearch()) {
            mMenu2.findItem(R.id.search).setVisible(true);
        }
    }
}

From source file:com.lastsoft.plog.GamesFragment.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Get item selected and deal with it
    switch (item.getItemId()) {
    case android.R.id.home:
        //called when the up affordance/carat in actionbar is pressed
        mActivity.onBackPressed();//from w ww .  j  a  v a 2  s  .c om
        return true;
    case R.id.random_game:
        //select random bucket list game
        SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(mActivity);

        List<Game> theGames = mAdapter.getGames();
        int min = 0;
        int max = theGames.size();
        Random r = new Random();
        int randomGame;

        if (!app_preferences.getBoolean("bucket_list_weight", false)) {
            randomGame = r.nextInt(max - min) + min;
        } else {
            //build weights
            int[] weightHash = new int[max];
            int weightedMax = 0;
            for (int i = 1; i <= max; i++) {
                weightedMax = weightedMax + i;
                weightHash[i - 1] = weightedMax;
            }

            randomGame = r.nextInt(weightedMax - min) + min;

            for (int j = max - 1; j >= 0; j--) {
                if (randomGame < weightHash[j]) {
                    //it may fall in this range
                    //see if it's larger than the next one
                    //if this one is zero, we found it
                    if (j == 0) {
                        randomGame = j;
                        break;
                    } else if (randomGame > weightHash[j - 1]) {
                        randomGame = j;
                        break;
                    } else if (randomGame == weightHash[j - 1]) {
                        randomGame = j - 1;
                        break;
                    }
                }
            }
        }

        Snackbar.make(mCoordinatorLayout,
                getString(R.string.random_game_to_play) + theGames.get(randomGame).gameName,
                Snackbar.LENGTH_LONG).show(); // Do not forget to show!
        return true;
    case R.id.sort:
        View menuItemView = mActivity.findViewById(R.id.sort);
        PopupMenu popup = new PopupMenu(mActivity, menuItemView);
        popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()) {
                case R.id.sort_az:
                    sortType = 0;
                    mAdapter.updateData(
                            mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
                    mRecyclerView.scrollToPosition(0);
                    if (mSearch != null) {
                        mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                                + getString(R.string.filter_games));
                    }
                    return true;
                case R.id.sort_za:
                    sortType = 1;
                    mAdapter.updateData(
                            mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
                    mRecyclerView.scrollToPosition(0);
                    return true;
                case R.id.sort_plays_x0:
                    sortType = 2;
                    mAdapter.updateData(
                            mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
                    mRecyclerView.scrollToPosition(0);
                    return true;
                case R.id.sort_plays_0x:
                    sortType = 3;
                    mAdapter.updateData(
                            mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
                    mRecyclerView.scrollToPosition(0);
                    return true;
                case R.id.sort_last_played_newold:
                    sortType = 4;
                    mAdapter.updateData(
                            mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
                    mRecyclerView.scrollToPosition(0);
                    return true;
                case R.id.sort_last_played_oldnew:
                    sortType = 5;
                    mAdapter.updateData(
                            mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
                    mRecyclerView.scrollToPosition(0);
                    return true;
                }
                return false;
            }
        });
        MenuInflater inflater = popup.getMenuInflater();
        inflater.inflate(R.menu.games_sort, popup.getMenu());
        if (playListType == 4) {
            //remove sort by plays
            popup.getMenu().getItem(2).setVisible(false);
            ;
            popup.getMenu().getItem(3).setVisible(false);
            ;
        }
        popup.show();
        return true;
    case R.id.show_expansions:
        if (showExpansions) {
            //currently showing expansions
            //trying to hide them
            //make it say show expansions
            item.setTitle(getString(R.string.show_expansions));
            item.setIcon(R.drawable.ic_visibility);
            playListType = playListType_Holder;
            mAdapter.updateData(mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
            if (mSearch != null) {
                mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                        + getString(R.string.filter_games));
            }
            showExpansions = false;
        } else {
            //currently hiding expansions
            //trying to show them
            //make it say hide expansions
            item.setTitle(getString(R.string.hide_expansions));
            item.setIcon(R.drawable.ic_visibility_off);
            playListType_Holder = playListType;
            if (playListType == 4) {
                playListType = 5;
            } else {
                playListType = 3;
            }
            mAdapter.updateData(mAdapter.generateGameList(mSearchQuery, playListType, sortType, currentYear));
            if (mSearch != null) {
                mSearch.setHint(getString(R.string.filter) + mAdapter.getItemCount()
                        + getString(R.string.filter_games));
            }
            showExpansions = true;
        }
        return true;
    }
    return false;
}