2016-12-03 37 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(); 
    } 
}