0

在Web視圖中,我加載了一個本地index.html文件,並將使用javaScript的HTML內容從遠程加入Webview。 我想要執行一些任務,如顯示工具提示,當用戶點擊Webview包含的元素時,警告框額外。這聽起來像它有非常簡單的解決方案。但我能夠這樣做! 謝謝!Android - Webview元素onClick事件不會觸發?

回答

0

添加的WebView到您的應用程序

<?xml version="1.0" encoding="utf-8"?> 
<WebView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/webview" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
/> 

在JAVA加載URL

WebView myWebView = (WebView) findViewById(R.id.webview); 
myWebView.loadUrl("http://www.example.com"); 

添加Internet權限

<manifest ... > 
<uses-permission android:name="android.permission.INTERNET" /> 
... 

在網頁視圖啓用javascript

WebView myWebView = (WebView) findViewById(R.id.webview); 
WebSettings webSettings = myWebView.getSettings(); 
webSettings.setJavaScriptEnabled(true); 

發出的接口

public class WebAppInterface { 
Context mContext; 

/** Instantiate the interface and set the context */ 
WebAppInterface(Context c) { 
    mContext = c; 
} 

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

您可以將這個類綁定到與addJavascriptInterface網頁視圖運行的JavaScript()並命名界面的Android。例如:

WebView webView = (WebView) findViewById(R.id.webview); 
webView.addJavascriptInterface(new WebAppInterface(this), "android"); 

在HTML

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" /> 

<script type="text/javascript"> 
    function showAndroidToast(toast) { 
     Android.showToast(toast); 
    } 
</script> 

希望這有助於你

來源https://developer.android.com/guide/webapps/webview.html#AddingWebView

+0

我並不需要一個接口作爲工具提示和警告顯示在HTML沒有的Andorid原生。 – Tulsi

1

shouldOverrideUrlLoading

前。

@Override 
public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     if(url!= && url.endWith("your_url.html")) { 

     //your tootip, alertIDialog, etc. 

     // return true to report that we have intercepted the event 
     return true; 
     } 
     return super.shouldOverrideUrlLoading(view, url); 

https://developer.android.com/reference/android/webkit/WebViewClient.html#shouldOverrideUrlLoading(android.webkit.WebView,android.webkit.WebResourceRequest)