如何在ActionMode覆盖中获取webview的选定文本 [英] How to get the selected text of webview in ActionMode override
问题描述
我正在上下文操作菜单中添加一些自定义菜单项.我需要使用在 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();
}
}
我想使用用户在 webview 中选择的词来搜索我的网站,但我无法找到获取所选文本的方法.我怎么能得到那个,请任何人帮忙.
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);
}
});
在较旧的版本中,您唯一的选择是自定义 javascript 接口,其中包含一个接受 String
的方法,您应该通过传递相同内容的 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屋!