android - 选择文本上的 webview 上下文菜单

标签 android menu android-webview

我一直在尝试自定义 webview 的上下文菜单,在 webview 中选择文本时会出现该菜单。

基本上我想在菜单中添加或删除项目。并在项目点击时添加一些自定义事件。

我已经尝试了一些类似下面链接的解决方案,但没有成功。 我最终得到的只是一个对话菜单。

https://developer.android.com/guide/topics/ui/menus.html#CAB

enter image description here

最佳答案

经过反复试验,我得出了一个合理的解决方案。 只是为了完整起见而将其张贴在这里,以防万一有人遇到类似的问题。

解决方案是创建一个我使用 PopupWindow 实现的替代菜单。 而我,使用 GestureDetector 在长按事件上调用它。

myWebView.setWebChromeClient(new MyWebChromeClient());
mGestureDetector = new GestureDetector(getActivity(), new CustomGestureListener());
mGestureDetector = new GestureListener(getActivity(),myWebView);
final GestureDetector gd = new GestureDetector(getActivity(), mGestureDetector);

    //====== web-view popup menu
    myWebView.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            gd.onTouchEvent(motionEvent);

            return false;
        }
    });

Gesture Listener 非常基础,可以找到代码here

与 web View 数据的其余交互是使用 JavaScript 完成的,使用下面的代码,更多信息可以在 google dev guide 中找到。

WebView xview = (WebView)view;
xview.loadUrl("javascript:alert(showAndroidToast('underline'))");

好吧,这已经为我完成了工作,结果如下图所示,希望对某人有所帮助。

或者除非有人有更好的解决方案/代码。

enter image description here

关于android - 选择文本上的 webview 上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56344862/

相关文章:

android - 什么是更好的多线程方法

android - 使用 Android NDK 将文件写入 SDcard 以外的位置?

Android Bluetooth Low Energy 获取对特定请求的响应

javascript - 如何使用 Javascript 将开关设置为关闭?

javascript - 如何在 WebView 中加载 Javascript

android - 连接到互联网后如何自动刷新网页 View

加载 WebView 时的 Android 进度条

java - 滚动后自定义 ListView 崩溃

service - Prism 应用程序 CAL 中的菜单服务

jquery - 向左和向右滑动移动设备菜单