How to override web view text selection menu in android

后端 未结 4 1893
有刺的猬
有刺的猬 2020-12-15 06:01

The basic android\'s web text selection menu is as shown in image attached below. It has options like copy, share, select all, web search.

I want to over ri

4条回答
  •  情歌与酒
    2020-12-15 06:18

    what you need is action mode, in activity:

        @Override
        public void onActionModeStarted(ActionMode mode) {
            Menu menu = mode.getMenu();
    
            // you can remove original menu: copy, cut, select all, share ... or not
            menu.clear();
    
            // here i will get text selection by user
            menu.add(R.string.action_menu_preview_card)
                    .setEnabled(true)
                    .setVisible(true)
                    .setOnMenuItemClickListener(item -> {
                        if (mWebview != null) {
                            mWebview.evaluateJavascript("window.getSelection().toString()", value -> {
                                value = StringUtil.trimToNull(value);
                                if (value != null) {
                                    // do something about user select
                                }
                            });
                        }
                        // Post a delayed runnable to avoid a race condition
                        // between evaluateScript() result and mode.finish()
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mode.finish();
                            }
                        }, 200);
                        return true;
                    });
            super.onActionModeStarted(mode);
        }
    

    i has test it above android 21, this can handle action mode menu click, and mode.getMenuInflater().inflate(...) can't do it.

提交回复
热议问题