0

As we know, by default, after selecting some text on views, android displays Contextual Action Bar (CAB) with some default options, such as: copy, cut, select all...

Now, I want to have an application (that has only 2 options: ON/OFF), If I turn it ON, Some other options will be added to default CAB. If I turn it OFF, my custom options will be removed from Android default CAB.

My question is: Is it possible to Add/Remove some options to this default CAB? How can I make above application?

Thank you!

Toan Tran Van
  • 695
  • 1
  • 7
  • 25
  • 1
    [TextView.setCustomSelectionActionModeCallback](http://stackoverflow.com/a/22833303/420015) is what you're looking for. – adneal Apr 16 '14 at 17:02
  • How can I apply this change to all TextView for all applications? As i mentioned, I want to make an application with only 2 options ON and OFF: If I select ON, some options will be add to CAB, If I select OFF, they will be moved. Thank you! – Toan Tran Van Apr 16 '14 at 17:07

1 Answers1

0

You'll have to use the setCustomSelectionActionModeCallback on each of your TextViews.

You can have a boolean:

boolean on = true;

Then create a method that actually edits the CAB like so:

private void editContextualActionBar(ActionMode actionMode, Menu menu) {
    if (on) {
        // adds a new menu item to the CAB
        // add(int groupId, int itemId, int order, int titleRes)
        menu.add(0, R.id.action_to_be_performed, 1, R.string.action_name);
    } else {
        // removes the new menu item
        menu.removeItem(R.id.action_to_be_performed);
    }
}

Finally, call the Callback on your TextView with the editContextualActionBar method in onCreateActionMode and perform the menu action in onActionItemClicked:

textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
        @Override
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            editContextualActionBar(mode, menu);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
                case R.id.action_to_be_performed:
                    // perform action
                    return true;
                default:
                    break;
            }
            return false;
        }

        @Override
        public void onDestroyActionMode(ActionMode mode) {

        }
    });
moyheen
  • 702
  • 7
  • 10