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)