在webView android中收听选择文本更改

时间:2016-12-03 11:21:31

标签: android webview

我正在尝试在WebView Android中更改文本选择时通知用户。

我尝试使用setOnTouchListener并听取

android.view.MotionEvent.ACTION_UP

并使用以下方法将上一个选择文字与修补后的新文本进行比较:

webview.loadUrl("javascript:js.callback(window.getSelection().toString())");

webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(), "Android");
public class WebAppInterface {
        @JavascriptInterface
        public void callback(String value) {
            Log.d(getClass().getName(), value);
            selected = value;
            if (selected.length() > 0) {
                Snackbar.make(findViewById(android.R.id.content), selected, Snackbar.LENGTH_SHORT).show();
            }
        }
}

但我有问题,当用户拖动/更改选择光标时,OnTouch未被触发

1 个答案:

答案 0 :(得分:0)

我已经为我的问题找到了足够的解决方案,但仍然不知道为什么onTouch在拖动光标时没有被触发。

在这里,我使用setOnInterval()每隔1000毫秒检查一次选择文字,如果有变化,则会触发WebAppInterface

myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(), "Android");
myWebView.loadData("Logcat is a tool that dumps a log of system messages. The messages include a stack trace when the device throws an error, as well as log messages written from your application and those written using JavaScript console APIs" +
        "<script>" +
        "var text='';setInterval(function(){ if(window.getSelection().toString() && text!==window.getSelection().toString()){text=window.getSelection().toString();console.log(text);Android.showToast(text); }}, 1000);" +
        "</script>" +,"text/html; charset=UTF-8", null);
myWebView.setWebChromeClient(new WebChromeClient() {
    public void onConsoleMessage(String message, int lineNumber, String sourceID) {
        Log.d("MyApplication", message );
    }
});

public class WebAppInterface {
    /** Show a toast from the web page */
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(MainActivity.this, toast, Toast.LENGTH_SHORT).show();
    }
}