【问题标题】:Android - Webview Element onClick event is not triggering?Android - Webview 元素 onClick 事件未触发?
【发布时间】:2017-04-12 11:38:58
【问题描述】:

在 Webview 中,我正在加载本地 index.html 文件并使用 javaScript 从远程将 HTML 内容添加到 Webview。 当用户单击 Webview 包含的元素时,我想执行一些任务,例如显示工具提示、警告框。 P.S 听起来它有非常直接的解决方案。但我可以这样做! 谢谢!

【问题讨论】:

    标签: android android-layout webview android-webview onclicklistener


    【解决方案1】:

    将 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() 将此类绑定到在您的 WebView 中运行的 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

    【讨论】:

    • 我不需要界面,因为工具提示和警报以 HTML 而非 Andorid 原生显示。
    【解决方案2】:

    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)

    【讨论】:

      猜你喜欢
      • 2021-05-14
      • 2016-06-23
      • 2012-12-19
      • 1970-01-01
      • 2015-07-25
      • 2020-01-31
      • 2013-04-30
      • 2011-02-05
      • 1970-01-01
      相关资源
      最近更新 更多