thisiscrazy4
thisiscrazy4

Reputation: 1965

Remove menu options from Contextual Action Bar

When selecting text in an android text view, a contextual action bar comes up with options to copy, cut, select all, share, etc. Is there a way to remove some of these options in my app?

Upvotes: 1

Views: 2820

Answers (2)

Samuel Agbede
Samuel Agbede

Reputation: 380

If you want to clear the default icons, You simply use menu.clear(). For instance altering the code above, we have private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

public boolean onCreateActionMode(ActionMode mode, Menu menu) {
    menu.clear;
    ...

    return true;
}

To remove a specific icon, you need to have the id of that icon. It would be something like menu.removeItem(android.R.id.copy) or something.

Upvotes: 0

Krylez
Krylez

Reputation: 17820

You can inflate your own menu and then hide all the items that OS inserts.

First, keep track of all the IDs for your menu items:

List<Integer> mOptionsList = new ArrayList<Integer>();

/* put these two lines in onCreate() */
mOptionsList.add(R.id.my_option_1);
mOptionsList.add(R.id.my_option_2);

Then, hide any MenuItem that isn't yours in onPrepare:

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.my_contectual_menu, menu);
        return true;
    }

    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        for (int i = 0; i < menu.size(); i++) {
            MenuItem item = menu.getItem(i);
            if (!mOptionsList.contains(item.getItemId()))
                item.setVisible(false);
        }
        return false;
    }

    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {
            case R.id.my_option_1: {
                /* do something for option 1 */
                break;
            }
            case R.id.my_option_2: {
                /* do something for option 2 */
                break;
            }
            default:
                return false;
        }
    }

    public void onDestroyActionMode(ActionMode mode) {}
};

Upvotes: 3

Related Questions