2016-12-03 73 views
0

我试图在WebView Android中的文本选择更改时通知用户。收听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不能点火d

回答

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(); 
    } 
}