Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overflow button forces Action Mode to finish

I have an EditText and I want the user to be able to select some text and apply some basic formatting to the selected text (bold, italic, etc). I still want the standard copy, cut, paste options to show, though. I read somewhere in the Android documentation that to do this, you should call setCustomSelectionActionModeCallback() on the EditText and pass it an ActionModeCallback(), so that's what I did. Here's my code:

In my activity's onCreate() method:

myEditText.setCustomSelectionActionModeCallback(new TextSelectionActionMode());

Callback declaration:

private class TextSelectionActionMode implements ActionMode.Callback {
    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        return false;
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        menu.add("Bold");
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }
}

The problem I'm having is that when I click on the overflow button (to access my "Bold" menu item), the ActionMode gets closed immediately. If I set it to always show as an action, using this:

MenuItem bold = menu.add("Bold");
bold.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);

It works fine and I can click on it (though it obviously does nothing). What am I missing here?

Edit: Just wanted to add that I run into the exact same problem if I actually inflate a menu instead of adding menu items programmatically. Once again, though, the problem goes away if I force it to always show as an action.

like image 949
mturco Avatar asked Feb 27 '12 01:02

mturco


2 Answers

It's frameworks issue. If textview receive 'focus changed' event, then textview stop the action mode. When overflow popup is shown, textview miss focus.

like image 68
w.A Avatar answered Nov 18 '22 13:11

w.A


This issue has been solved in Android 6.0. However you should use ActionMode.Callback2 as described here in Android 6.0.

For Android 5.x and below, I recommend this workaround: add a button to Toolbar or ActionBar which records the current selection and then open another context menu.

this.inputText_selectionStart = inputText.getSelectionStart();
this.inputText_selectionEnd = inputText.getSelectionEnd();
registerForContextMenu(inputText);
openContextMenu(inputText);
unregisterForContextMenu(inputText);
like image 30
Mygod Avatar answered Nov 18 '22 14:11

Mygod