Android webview覆盖startActionMode但保持默认关闭文本选择

时间:2014-12-07 13:07:14

标签: android text webview textselection android-actionmode

在搜索了类似的问题后,我放弃了,并决定问自己,如果有现有答案,请通知我。

我有一个WebView,我需要覆盖默认的actionMode,我遵循了许多Q&在这里,一切都运行良好,直到我注意到actionMode的行为中缺少一些非常具体的东西。文本选择的解除事件仅在用户按下"后退按钮"或者"完成"在动作模式上。在Default actionMode中,当用户在所选文本外部按下时,actionMode也会关闭,而我无法实现并且不确定如何在不使用复杂内容和编写额外代码行而不是使用" super&#34的情况下实现它;用户在所选文本外部按下时忽略文本选择的行为。

希望你能提供帮助,谢谢你。

我的WebView与覆盖的startActionMode:

@Override
public ActionMode startActionMode(ActionMode.Callback callback) {

    /*
     * When running Ice Cream Sandwich (4.0) or Jelly Bean (4.1 - 4.3),
     * there is a hidden class called 'WebViewClassic' that draws the
     * selection. In order to clear the selection, save the callback from
     * Classic so it can be destroyed later.
     */
    // Check the class name because WebViewClassic.SelectActionModeCallback
    // is not public API.
    String name = callback.getClass().toString();
    if (name.contains("SelectActionModeCallback")) {
        webViewDefaultActionModeCallBack = callback;
    }

    if (mActionMode == null) {
        mActionMode = super.startActionMode(mActionModeCallback);
    }
    return mActionMode;
}

我的ActionModeCallback:

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {

    // Called when the action mode is created; startActionMode() was called
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {

        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.my_menu, menu);
        return true;
    }

    // Called each time the action mode is shown. Always called after
    // onCreateActionMode, but
    // may be called multiple times if the mode is invalidated.
    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {

        return false; // Return false if nothing is done
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        switch (item.getItemId()) {

            case R.id.item1:
                // do something 
                break;

            case R.id.item2:
                // do something 
                break;
        }

        mode.finish();
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {

        mActionMode = null;

        // Semi-hack in order to clear the selection
        // when running Android earlier than KitKat.
        if (webViewDefaultActionModeCallBack != null) {
            webViewDefaultActionModeCallBack.onDestroyActionMode(mode);
        }
    }
};

0 个答案:

没有答案