如何在ActionMode中获取选定的WebView文本 [英] How to get the selected text of webview in ActionMode override
问题描述
我要在上下文操作菜单"中添加一些自定义菜单项.我需要提供一个Web搜索功能,其中包含在WebView中选择的单词.
I am adding some custom menu items in the Contextual Action Menu. I need to give a web search feature with the words selected in the WebView.
我使用此代码覆盖ActionMode.
I override the ActionMode using this code.
@Override
public void onActionModeStarted(ActionMode mode) {
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
if (mActionMode == null) {
mActionMode = mode;
Menu menu = mode.getMenu();
mode.getMenuInflater().inflate(R.menu.menu_search, menu);
}
}
super.onActionModeStarted(mode);
}
public void onContextualMenuItemClicked(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_search:
//HERE I WANT TO GET THE TEXT: HOW CAN I?
break;
}
if (mActionMode != null) {
mActionMode.finish();
}
}
我想使用用户在Web视图中选择的单词搜索我的网站,但我无法获取所选文本.我怎么能得到,请任何人帮助.
I want to search my site using the word selected by the user in the webview, but I couln't get the way to get the selected text. How could i get that, any one please help.
提前谢谢.
推荐答案
从 WebView
获取文本选择的唯一方法是基于javascript.这不是特定于操作模式的,这是应该根据 WebView
开发人员的观点来检索 WebView
文本选择的方式.他们故意决定不提供API来从Java中访问文本选择.
The only way to get text selection from a WebView
is based on javascript. This is not specific to the action mode, this is how WebView
text selection is supposed to be retrieved according to WebView
developers' point of view. They deliberately decided to not provide an API to access text selection from Java.
该解决方案包括2种方法.
The solution comprise 2 approaches.
使用Android API> = 19,您可以使用 evaluateJavascript
:
With Android API >= 19 you can use evaluateJavascript
:
webview.evaluateJavascript("(function(){return window.getSelection().toString()})()",
new ValueCallback<String>()
{
@Override
public void onReceiveValue(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
});
在较旧的版本上,您唯一的办法是使用一个接受 String
的单一方法的自定义javascript接口,您应通过传递相同内容的 webview.loadUrl
进行调用:>
On older builds your only resort is a custom javascript interface with a single method accepting String
, which you should call via webview.loadUrl
passing the same thing:
webview.loadUrl("javascript:js.callback(window.getSelection().toString())");
其中 js
是附加的javascript接口:
where js
is the attached javascript interface:
webview.getSettings().setJavaScriptEnabled(true);
webview.addJavascriptInterface(new WebAppInterface(), "js");
和
public class WebAppInterface
{
@JavascriptInterface
public void callback(String value)
{
Log.v(TAG, "SELECTION:" + value);
}
}
这篇关于如何在ActionMode中获取选定的WebView文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!