Example usage for android.view MenuItem setOnMenuItemClickListener

List of usage examples for android.view MenuItem setOnMenuItemClickListener

Introduction

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

Prototype

public MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener);

Source Link

Document

Set a custom listener for invocation of this menu item.

Usage

From source file:net.nightwhistler.pageturner.activity.ReadingFragment.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

    // This is a hack to give the longclick handler time
    // to find the word the user long clicked on.

    if (this.selectedWord != null) {

        final CharSequence word = this.selectedWord.getText();
        final int startIndex = this.selectedWord.getStartOffset();
        final int endIndex = this.selectedWord.getEndOffset();

        String header = String.format(getString(R.string.word_select), selectedWord.getText());

        menu.setHeaderTitle(header);// w  w  w .  jav a 2 s .co  m

        if (isDictionaryAvailable()) {
            android.view.MenuItem item = menu.add(getString(R.string.dictionary_lookup));
            item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(android.view.MenuItem item) {
                    lookupDictionary(word.toString());
                    return true;
                }
            });
        }

        menu.add(R.string.highlight).setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem menuItem) {

                highLight(startIndex, endIndex, word.toString());

                return false;
            }
        });

        android.view.MenuItem newItem = menu.add(getString(R.string.wikipedia_lookup));
        newItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupWikipedia(word.toString());
                return true;
            }
        });

        android.view.MenuItem newItem3 = menu.add(getString(R.string.lookup_wiktionary));
        newItem3.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupWiktionary(word.toString());
                return true;
            }
        });

        android.view.MenuItem newItem2 = menu.add(getString(R.string.google_lookup));
        newItem2.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupGoogle(word.toString());
                return true;
            }
        });

        this.selectedWord = null;
    }
}

From source file:net.zorgblub.typhon.fragment.ReadingFragment.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

    // This is a hack to give the longclick handler time
    // to find the word the user long clicked on.

    if (this.selectedWord != null && !this.config.isRikaiEnabled()) {

        final CharSequence word = this.selectedWord.getText();
        final int startIndex = this.selectedWord.getStartOffset();
        final int endIndex = this.selectedWord.getEndOffset();

        String header = String.format(getString(R.string.word_select), selectedWord.getText());

        menu.setHeaderTitle(header);//from   w  w w.  j a v a  2 s.c o  m

        if (isDictionaryAvailable()) {
            android.view.MenuItem item = menu.add(getString(R.string.dictionary_lookup));
            onMenuPress(item).thenDo(() -> lookupDictionary(word.toString()));
        }

        menu.add(R.string.highlight).setOnMenuItemClickListener(item -> {
            highLight(startIndex, endIndex, word.toString());
            return false;
        });

        android.view.MenuItem lookUpWikipediaItem = menu.add(getString(R.string.wikipedia_lookup));

        onMenuPress(lookUpWikipediaItem).thenDo(() -> lookupWikipedia(word.toString()));

        android.view.MenuItem lookUpWiktionaryItem = menu.add(getString(R.string.lookup_wiktionary));

        lookUpWiktionaryItem.setOnMenuItemClickListener(item -> {
            lookupWiktionary(word.toString());
            return true;
        });

        android.view.MenuItem lookupGoogleItem = menu.add(getString(R.string.google_lookup));

        lookupGoogleItem.setOnMenuItemClickListener(item -> {
            lookupGoogle(word.toString());
            return true;
        });

        this.selectedWord = null;
    }
}

From source file:com.aujur.ebookreader.activity.ReadingFragment.java

@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {

    // This is a hack to give the longclick handler time
    // to find the word the user long clicked on.

    if (this.selectedWord != null) {

        final CharSequence word = this.selectedWord.getText();
        final int startIndex = this.selectedWord.getStartOffset();
        final int endIndex = this.selectedWord.getEndOffset();

        String header = String.format(getString(R.string.word_select), selectedWord.getText());

        menu.setHeaderTitle(header);//from   w  w w  .j a  v a2s.co m

        if (isDictionaryAvailable()) {
            android.view.MenuItem item = menu.add(getString(R.string.dictionary_lookup));
            item.setOnMenuItemClickListener(new OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(android.view.MenuItem item) {
                    lookupDictionary(word.toString());
                    return true;
                }
            });
        }

        menu.add(R.string.highlight).setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem menuItem) {

                highLight(startIndex, endIndex, word.toString());

                return false;
            }
        });

        android.view.MenuItem newItem = menu.add(getString(R.string.wikipedia_lookup));
        newItem.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupWikipedia(word.toString());
                return true;
            }
        });

        android.view.MenuItem newItem3 = menu.add(getString(R.string.lookup_wiktionary));
        newItem3.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupWiktionary(word.toString());
                return true;
            }
        });

        android.view.MenuItem newItem2 = menu.add(getString(R.string.google_lookup));
        newItem2.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupGoogle(word.toString());
                return true;
            }
        });

        android.view.MenuItem newItem4 = menu.add(getString(R.string.direitonet_lookup));
        newItem4.setOnMenuItemClickListener(new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                lookupLawDictionary(word.toString());
                return true;
            }
        });

        this.selectedWord = null;
    }
}

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();/*from   w  w  w.  j  av  a  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:org.mozilla.gecko.BrowserApp.java

/**
 * Add the provided item to the provided menu, which should be
 * the root (mMenu)./*from  w  ww. j  ava  2 s.  c  o m*/
 */
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:org.mozilla.gecko.GeckoApp.java

@Override
public boolean onPrepareOptionsMenu(Menu aMenu) {
    Iterator<ExtraMenuItem> i = sExtraMenuItems.iterator();
    while (i.hasNext()) {
        final ExtraMenuItem item = i.next();
        if (aMenu.findItem(item.id) == null) {
            final MenuItem mi = aMenu.add(Menu.NONE, item.id, Menu.NONE, item.label);
            if (item.icon != null) {
                if (item.icon.startsWith("data")) {
                    byte[] raw = GeckoAppShell.decodeBase64(item.icon.substring(22),
                            GeckoAppShell.BASE64_DEFAULT);
                    Bitmap bitmap = BitmapFactory.decodeByteArray(raw, 0, raw.length);
                    BitmapDrawable drawable = new BitmapDrawable(bitmap);
                    mi.setIcon(drawable);
                } else if (item.icon.startsWith("jar:") || item.icon.startsWith("file://")) {
                    GeckoAppShell.getHandler().post(new Runnable() {
                        public void run() {
                            try {
                                URL url = new URL(item.icon);
                                InputStream is = (InputStream) url.getContent();
                                Drawable drawable = Drawable.createFromStream(is, "src");
                                mi.setIcon(drawable);
                            } catch (Exception e) {
                                Log.w(LOGTAG, "onPrepareOptionsMenu: Unable to set icon", e);
                            }/*from  w  w  w .j  av  a 2 s  . c o m*/
                        }
                    });
                }
            }
            mi.setOnMenuItemClickListener(item);
        }
    }

    if (!sIsGeckoReady)
        aMenu.findItem(R.id.settings).setEnabled(false);

    Tab tab = Tabs.getInstance().getSelectedTab();
    MenuItem bookmark = aMenu.findItem(R.id.bookmark);
    MenuItem forward = aMenu.findItem(R.id.forward);
    MenuItem share = aMenu.findItem(R.id.share);
    MenuItem saveAsPDF = aMenu.findItem(R.id.save_as_pdf);
    MenuItem charEncoding = aMenu.findItem(R.id.char_encoding);

    if (tab == null) {
        bookmark.setEnabled(false);
        forward.setEnabled(false);
        share.setEnabled(false);
        saveAsPDF.setEnabled(false);
        return true;
    }

    bookmark.setEnabled(true);
    bookmark.setCheckable(true);

    if (tab.isBookmark()) {
        bookmark.setChecked(true);
        bookmark.setIcon(R.drawable.ic_menu_bookmark_remove);
    } else {
        bookmark.setChecked(false);
        bookmark.setIcon(R.drawable.ic_menu_bookmark_add);
    }

    forward.setEnabled(tab.canDoForward());

    // Disable share menuitem for about:, chrome: and file: URIs
    String scheme = Uri.parse(tab.getURL()).getScheme();
    boolean enabled = scheme != null
            && !(scheme.equals("about") || scheme.equals("chrome") || scheme.equals("file"));
    share.setEnabled(enabled);

    // Disable save as PDF for about:home and xul pages
    saveAsPDF.setEnabled(!(tab.getURL().equals("about:home")
            || tab.getContentType().equals("application/vnd.mozilla.xul+xml")));

    charEncoding.setVisible(GeckoPreferences.getCharEncodingState());

    return true;
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private synchronized void updateFromFilterEdit() {
    final SubMenu filters = mFilterItem.getSubMenu();

    for (int i = 0; i < FILTER_MAX_ID; i++) {
        filters.removeItem(i);/*from ww  w.ja  v  a 2 s .co  m*/
    }

    ArrayList<ChannelFilterValues> channelFilterList = new ArrayList<ChannelFilterValues>();
    SharedPreferences filterPreferences = PrefUtils.getSharedPreferences(PrefUtils.TYPE_PREFERENCES_FILTERS,
            TvBrowser.this);
    Map<String, ?> filterValues = filterPreferences.getAll();

    for (String key : filterValues.keySet()) {
        Object values = filterValues.get(key);

        if (key.startsWith("filter.") && values instanceof String && values != null) {
            channelFilterList.add(new ChannelFilterValues(key, (String) values));
        }
    }

    Collections.sort(channelFilterList, ChannelFilterValues.CHANNEL_FILTER_VALUES_COMPARATOR);

    int groupId = 3;
    int id = 1;

    mAllFilter = new ChannelFilterValues(SettingConstants.ALL_FILTER_ID,
            getString(R.string.activity_edit_filter_list_text_all), "");

    MenuItem all = filters.add(groupId, id++, groupId, mAllFilter.toString());
    all.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            updateChannelFilter(mAllFilter, R.drawable.ic_filter_default);
            item.setChecked(true);
            return true;
        }
    });

    if (mCurrentChannelFilterId == null || mAllFilter.getId().endsWith(mCurrentChannelFilterId)) {
        all.setChecked(true);
    }

    for (final ChannelFilterValues filter : channelFilterList) {
        MenuItem item = filters.add(groupId, id++, groupId, filter.toString());

        if (mCurrentChannelFilterId != null && filter.getId().endsWith(mCurrentChannelFilterId)) {
            mFilterItem.setIcon(R.drawable.ic_filter_on);
            item.setChecked(true);
        }

        item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                updateChannelFilter(filter, R.drawable.ic_filter_on);
                item.setChecked(true);

                return true;
            }
        });
    }

    FILTER_MAX_ID = id;

    filters.setGroupCheckable(groupId, true, true);
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void editDontWantToSee() {
    if (!SettingConstants.UPDATING_FILTER) {
        Set<String> currentExclusions = PrefUtils.getStringSetValue(R.string.I_DONT_WANT_TO_SEE_ENTRIES, null);

        final ArrayList<ExclusionEdit> mCurrentExclusionList = new ArrayList<TvBrowser.ExclusionEdit>();

        if (currentExclusions != null && !currentExclusions.isEmpty()) {
            for (String exclusion : currentExclusions) {
                mCurrentExclusionList.add(new ExclusionEdit(exclusion));
            }//from   w w w.  j  a v  a  2  s.  c om
        }

        Collections.sort(mCurrentExclusionList);

        final ArrayAdapter<ExclusionEdit> exclusionAdapter = new ArrayAdapter<TvBrowser.ExclusionEdit>(
                TvBrowser.this, android.R.layout.simple_list_item_1, mCurrentExclusionList);

        View view = getLayoutInflater().inflate(R.layout.dont_want_to_see_exclusion_edit_list,
                getParentViewGroup(), false);

        ListView list = (ListView) view.findViewById(R.id.dont_want_to_see_exclusion_list);

        list.setAdapter(exclusionAdapter);

        final Runnable cancel = new Runnable() {
            @Override
            public void run() {
            }
        };

        AdapterView.OnItemClickListener onClickListener = new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final ExclusionEdit edit = exclusionAdapter.getItem(position);

                View editView = getLayoutInflater().inflate(R.layout.dont_want_to_see_edit,
                        getParentViewGroup(), false);

                final TextView exclusion = (TextView) editView.findViewById(R.id.dont_want_to_see_value);
                final CheckBox caseSensitive = (CheckBox) editView
                        .findViewById(R.id.dont_want_to_see_case_sensitve);

                exclusion.setText(edit.mExclusion);
                caseSensitive.setSelected(edit.mIsCaseSensitive);

                Runnable editPositive = new Runnable() {
                    @Override
                    public void run() {
                        if (exclusion.getText().toString().trim().length() > 0) {
                            edit.mExclusion = exclusion.getText().toString();
                            edit.mIsCaseSensitive = caseSensitive.isSelected();

                            exclusionAdapter.notifyDataSetChanged();
                        }
                    }
                };

                showAlertDialog(getString(R.string.action_dont_want_to_see), null, editView, null, editPositive,
                        null, cancel, false, false);
            }
        };

        list.setOnItemClickListener(onClickListener);
        list.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
                getMenuInflater().inflate(R.menu.don_want_to_see_context, menu);

                MenuItem item = menu.findItem(R.id.dont_want_to_see_delete);

                item.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        ExclusionEdit edit = exclusionAdapter
                                .getItem(((AdapterView.AdapterContextMenuInfo) item.getMenuInfo()).position);
                        exclusionAdapter.remove(edit);
                        exclusionAdapter.notifyDataSetChanged();

                        return true;
                    }
                });
            }
        });

        Thread positive = new Thread() {
            @Override
            public void run() {
                SettingConstants.UPDATING_FILTER = true;

                final NotificationCompat.Builder builder = new NotificationCompat.Builder(TvBrowser.this);
                builder.setSmallIcon(R.drawable.ic_stat_notify);
                builder.setOngoing(true);
                builder.setContentTitle(getResources().getText(R.string.action_dont_want_to_see));
                builder.setContentText(
                        getResources().getText(R.string.dont_want_to_see_refresh_notification_text));

                final int notifyID = 2;

                final NotificationManager notification = (NotificationManager) getSystemService(
                        Context.NOTIFICATION_SERVICE);
                notification.notify(notifyID, builder.build());

                updateProgressIcon(true);

                HashSet<String> newExclusions = new HashSet<String>();
                final ArrayList<DontWantToSeeExclusion> exclusionList = new ArrayList<DontWantToSeeExclusion>();

                for (ExclusionEdit edit : mCurrentExclusionList) {
                    String exclusion = edit.getExclusion();

                    newExclusions.add(exclusion);
                    exclusionList.add(new DontWantToSeeExclusion(exclusion));
                }

                new Thread() {
                    public void run() {
                        Cursor programs = getContentResolver().query(TvBrowserContentProvider.CONTENT_URI_DATA,
                                new String[] { TvBrowserContentProvider.KEY_ID,
                                        TvBrowserContentProvider.DATA_KEY_TITLE },
                                null, null, TvBrowserContentProvider.KEY_ID);
                        programs.moveToPosition(-1);

                        builder.setProgress(programs.getCount(), 0, true);
                        notification.notify(notifyID, builder.build());

                        ArrayList<ContentProviderOperation> updateValuesList = new ArrayList<ContentProviderOperation>();

                        int keyColumn = programs.getColumnIndex(TvBrowserContentProvider.KEY_ID);
                        int titleColumn = programs.getColumnIndex(TvBrowserContentProvider.DATA_KEY_TITLE);

                        DontWantToSeeExclusion[] exclusionArr = exclusionList
                                .toArray(new DontWantToSeeExclusion[exclusionList.size()]);

                        while (programs.moveToNext()) {
                            builder.setProgress(programs.getCount(), programs.getPosition(), false);
                            notification.notify(notifyID, builder.build());

                            String title = programs.getString(titleColumn);

                            boolean filter = UiUtils.filter(getApplicationContext(), title, exclusionArr);
                            long progID = programs.getLong(keyColumn);

                            ContentValues values = new ContentValues();
                            values.put(TvBrowserContentProvider.DATA_KEY_DONT_WANT_TO_SEE, filter ? 1 : 0);

                            ContentProviderOperation.Builder opBuilder = ContentProviderOperation.newUpdate(
                                    ContentUris.withAppendedId(TvBrowserContentProvider.CONTENT_URI_DATA_UPDATE,
                                            progID));
                            opBuilder.withValues(values);

                            updateValuesList.add(opBuilder.build());
                        }

                        notification.cancel(notifyID);

                        programs.close();

                        if (!updateValuesList.isEmpty()) {
                            try {
                                getContentResolver().applyBatch(TvBrowserContentProvider.AUTHORITY,
                                        updateValuesList);
                                UiUtils.sendDontWantToSeeChangedBroadcast(getApplicationContext(), true);
                                handler.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Toast.makeText(getApplicationContext(),
                                                R.string.dont_want_to_see_sync_success, Toast.LENGTH_LONG)
                                                .show();
                                    }
                                });
                            } catch (RemoteException e) {
                                e.printStackTrace();
                            } catch (OperationApplicationException e) {
                                e.printStackTrace();
                            }
                        }

                        updateProgressIcon(false);
                        SettingConstants.UPDATING_FILTER = false;
                    }
                }.start();

                Editor edit = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit();
                edit.putStringSet(getString(R.string.I_DONT_WANT_TO_SEE_ENTRIES), newExclusions);
                edit.commit();
            }
        };

        showAlertDialog(getString(R.string.action_dont_want_to_see_edit), null, view, null, positive, null,
                cancel, false, true);
    }
}