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.


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


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);

It is a filed Android bug: https://code.google.com/p/android/issues/detail?id=82640. That link contains a workaround. Fortunately this has been fixed in Android 6.0.

链接地址: http://www.djcxy.com/p/57782.html

上一篇: SQL选择或插入返回ID

下一篇: 溢出按钮强制动作模式完成