简体   繁体   English

如何向Android默认上下文操作栏添加更多选项

[英]How to add more options to Android default Contextual Action Bar

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... 众所周知,默认情况下,在视图上选择了一些文本后,Android会显示具有某些默认选项的上下文操作栏(CAB),例如:复制,剪切,全选...

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. 现在,我要有一个应用程序(只有2个选项:ON / OFF),如果我将其打开,则会将其他一些选项添加到默认的CAB中。 If I turn it OFF, my custom options will be removed from Android default CAB. 如果我将其关闭,则我的自定义选项将从Android默认CAB中删除。

My question is: Is it possible to Add/Remove some options to this default CAB? 我的问题是:是否可以向此默认CAB添加/删除某些选项? How can I make above application? 我该如何申请?

Thank you! 谢谢!

You'll have to use the setCustomSelectionActionModeCallback on each of your TextViews. 您必须在每个TextView上使用setCustomSelectionActionModeCallback

You can have a boolean: 您可以使用布尔值:

boolean on = true;

Then create a method that actually edits the CAB like so: 然后创建一个实际编辑CAB的方法,如下所示:

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: 最后,使用onCreateActionMode中的editContextualActionBar方法在TextView上调用回调,并在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) {

        }
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM