在文本选择中禁用android webview中的上下文操作栏

时间:2017-01-09 13:58:42

标签: android android-webview contextual-action-bar

如何在Web视图中禁用上下文操作栏?我希望文本选择功能保持原样,但我不希望上下文操作栏出现,我该如何禁用它?

enter image description here

使用此代码会隐藏上下文操作栏,但它看起来很糟糕(整个屏幕都在抖动),并且文本选择也没有保留。

    @Override
    public void onSupportActionModeStarted(ActionMode mode) {
    super.onSupportActionModeStarted(mode);
    mode.finish();
   }

如何禁用上下文操作栏?还有其他办法吗?

2 个答案:

答案 0 :(得分:1)

我知道回答问题已经很晚了,但是我发现它并可以正常工作。(我在5.0.1上对其进行了测试,它仍然可以正常工作)(以下代码只会清除复制,粘贴并从菜单中选择所有选项。 )

在将要在Webview中加载的html代码中插入错误的代码,

"<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n" +
 "<script>\n" +
            "$(function() {\n" +
            "  $(document.body).bind('touchstart', function(e) {\n" +
            "    var selection;\n" +
            "\n" +
            "    if (window.getSelection) {\n" +
            "      selection = window.getSelection();\n" +
            "    } else if (document.selection) {\n" +
            "      selection = document.selection.createRange();\n" +
            "    }\n" +
            "\n" +
            "    selection.toString() !== '' && ReaderJavaScript.onTextselectionEnded(true)\n" +
            "  });\n" +
            "});\n" +
            "</script>" 

请参见代码,我使用了ReaderJavaScript接口,该接口将充当js代码和活动之间的桥梁,以在ReaderJavaScript.onTextselectionEnded(true)调用时携带信息。 因此,每当用户选择终端时,它都会显示出来,届时您只需添加以下代码即可清除活动中的菜单,

 readerView.setTextSelectionFinishedListener(new ReaderView.TextSelectionFinishedListener() {
            @Override
            public void onTextSelectionEnded(boolean textSelectionEnded) {
                if (mActionMode != null){
                    if (mActionMode.getMenu() != null){
                        mActionMode.getMenu().clear();
                    }
                }
            }
        });

答案 1 :(得分:0)

只需手动删除它。

当触发旧操作模式栏时,视图层次结构将是:

view hierachy

所以只需通过以下代码修复不需要的层次结构

View p2th = Utils.getNthParent(root, 2);
if (p2th!=null && p2th.getId()==R.id.action_bar_root) {
    Utils.replaceView(Utils.getNthParent(root, 1), p2th);
}

其中 Utils.getNthParent 返回根视图的第 N 个父视图,而 Utils.replaceView 只是将操作栏根替换为我们的内容视图。

(在 android 4.4 和 5 上测试成功,没有闪烁或崩溃。)

多么天才的解决方案,如此简单又如此愚蠢……

相关问题