通过上下文操作栏获取 WebView 中选定的文本
众所周知,很难在 WebView 中获取选定的文本,因为 WebView 文本选择实际上是由私有类,WebTextView。
然而,随着最近发布的Android 4.0设计指南,似乎出现了一丝希望通过上下文操作栏(CAB)来实现这一目标。它说:
每当您允许用户通过长按选择数据时,请使用 CAB。您可以控制 CAB 的操作内容,以便插入您希望用户能够执行的操作。
我是否误解了这一点? 有没有办法通过 CAB 从 WebView 检索选定的文本?
长按并开始文本选择模式后,我当前可以检测 ActionMode
何时启动并修改原始复制/粘贴菜单
;但是,我不太清楚如何实际检索所选文本。
It's known to be difficult to get selected text in a WebView because WebView text selection is actually handled by a private class, WebTextView.
However, with the recently released Android 4.0 Design guidelines, there seems to be a glimmer of hope of achieving this through contextual action bars (CABs). It says:
Use CABs whenever you allow the user to select data via long press. You can control the action content of a CAB in order to insert the actions you would like the user to be able to perform.
Am I misinterpreting this? Is there a way to retrieve selected text from a WebView via a CAB?
After a long click and text selection mode begins, I can currently detect when the ActionMode
starts and modify the original copy/paste Menu
; however, I can't quite figure out how to actually retrieve the selected text.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用当前的 API 还无法做到这一点。
我为此提交了一个功能请求 - 问题 24841:WebView 应允许应用程序提供自定义上下文操作栏 http://code.google.com/p/android/issues/detail?id=24841
基本上,4.0 中的 WebView 硬编码了自己的上下文操作栏 (出租车)。该 CAB 有一个对 WebView 的引用,通过该引用,它可以获取选定的文本。我不确定您如何能够检测到 ActionMode 启动并修改菜单,但如果您能够完成所有这些,那么您就会陷入困境,因为 getSelection() 目前是包私有的。我将其作为一个单独的问题提交,并将其链接到上面的上一问题。
You can't do that yet with the current API.
I filed a feature request for this - Issue 24841: WebView should allow applications to supply a custom Contextual Action Bar http://code.google.com/p/android/issues/detail?id=24841
Basically, WebView in 4.0 has hardcoded its own Contextual Action Bar (CAB). That CAB has a reference back to the WebView and with that reference, it can get the selected text. I'm not sure how you were able to detect the ActionMode starting and modify the menu, but if you were able to do all of that, then you are stuck because getSelection() is package-private currently. I filed that as a separate issue and linked it to the previous issue above.
可以使用javascript获取选中的文本:window.getSelection(),并使用WebView的addJavascriptInterface函数返回结果。
You can use javascript to get the selected text: window.getSelection(), and use WebView's addJavascriptInterface function to return the result.
谢谢你的信息,我解决了一个难题..
我只是想在动作模式中添加一些功能。
以下是我的代码,可能对其他人有帮助。
thanks for your information, I have solved a hard issue..
I just want to add some function into the actionmode.
The following is my code, May be helpful to others.