【问题标题】:Android WebView showToast onButtonClickAndroid WebView showToast onButtonClick
【发布时间】:2015-04-21 18:09:08
【问题描述】:

我正在开发一个使用 WebView 来显示网页的应用程序。 该网页包含一个注册表单和一个“下一步”按钮。我想要 知道如果用户是否可以显示 Android toast 消息 按下一步,但未能填充输入区域或数据没有 不符合要求的标准。我已经编写了验证逻辑, 但我不确定 Toasts,有人能指点我吗 方向?

【问题讨论】:

    标签: android android-toast


    【解决方案1】:

    您可以通过实现一个简单的 JavaScript 界面来解决您的问题。下面是一个简单的示例。

    assets/button_demo.xml

    <html>
    <head></head>
    <body style="margin:0; padding:0;">
    <style type="text/css">
        #demo {
        height: 100%;
        width: 100%;
        margin-left: auto;
        margin-right: auto;
        overflow: auto;
        }
        #demo a {
        font-family: sans-serif;
        font-size: 8pt;
        width: 95%;
        height: 35px;
        display: block;
        margin-left: auto;
        margin-right: auto;
        text-align: center;
        padding: 5px;
        margin: 1px;
        border: 1px solid blue;
        text-decoration: none;
        color: blue;
        word-wrap: break-word;
    
        }
    </style>
    <script type="text/javascript">
    
        function showToast(str){
            Android.showToast(str);
        }
    
    </script>
    <div id="demo">
        <a href="javascript: showToast('test')">button</a>
    </div>
    </body>
    </html>
    

    activity_main.xml

    <RelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    
        <WebView
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:id="@+id/webView"
            android:layout_centerVertical="true"/>
    
    </RelativeLayout>
    

    MainActivity.java

    import android.app.Activity;
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import android.support.v7.app.ActionBarActivity;
    import android.text.TextUtils;
    import android.util.Log;
    import android.webkit.JavascriptInterface;
    import android.webkit.WebSettings;
    import android.webkit.WebView;
    import android.webkit.WebViewClient;
    import android.widget.Toast;
    
    import java.lang.ref.WeakReference;
    
    
    public class MainActivity extends ActionBarActivity {
    
        private static final String TAG = MainActivity.class.getSimpleName();
        private WebView webView;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            webView = (WebView) findViewById(R.id.webView);
            WebSettings webSettings = webView.getSettings();
            webSettings.setJavaScriptEnabled(true);
            webView.setWebViewClient(new MyWebClient());
            webView.addJavascriptInterface(new WebInterface(MainActivity.this), "Android");
            webView.loadUrl("file:///android_asset/button_demo.html");
        }
    
        private class MyWebClient extends WebViewClient {
    
    
            /**
             * It is a good idea to let proper web browsers handle URLs you don't know otherwise
             * you could be putting your users to danger by injecting JavaScript interface
             */
    
    
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
    
                //return super.shouldOverrideUrlLoading(view, url);
                Uri uri;
    
                try {
                    uri = Uri.parse(url);
                } catch (NullPointerException e) {
                    // let Android deal with this
                    return true;
                }
    
                String host = uri.getHost(); //Host is null when user clicked on email, phone number, ...
    
                if (host != null && host.equals("stackoverflow.com")) {
                    // This is my web site, so do not override; let my WebView load the page
                    return false;
                }
                else {
                    // Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs or anything else (email, phone number, ...)
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
            }
    
            @Override
            public void onPageFinished(WebView view, String url) {
                Log.d(TAG, "Page finished loading");
                super.onPageFinished(view, url);
            }
    
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                // No connection or HTTP error e.g. 404
                Log.d(TAG, "Received webview error: " + errorCode + " - " + description + " ; " + failingUrl);
            }
        }
    
        private final class WebInterface {
            /**
             * Caution: If you've set your targetSdkVersion to 17 or higher, you must
             * add the @JavascriptInterface annotation to any method that you want
             * available to your JavaScript (the method must also be public). If you do
             * not provide the annotation, the method is not accessible by your web page
             * when running on Android 4.2 or higher.
             */
    
            private WeakReference<Activity> mContextRef;
            private Toast toast;
    
            public WebInterface(Activity context) {
                this.mContextRef = new WeakReference<Activity>(context);
            }
    
            @JavascriptInterface
            public void showToast(final String toastMsg) {
    
                if (TextUtils.isEmpty(toastMsg) || mContextRef.get() == null) {
                    return;
                }
    
                // JavaScript doesn't run on the UI thread, make sure you do anything UI related like this
                // You don't need this for the Toast, but otherwise it's a good idea
                mContextRef.get().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
    
                        if (toast != null) {
                            toast.cancel();
                        }
    
                        toast = Toast.makeText(mContextRef.get(), toastMsg, Toast.LENGTH_SHORT);
                        toast.show();
                    }
                });
    
            }
    
    
        }
    }
    

    【讨论】:

    • Android.showToast(str); Android 中没有定义,因为结果将是一个 Javascript 错误,如“未捕获的 ReferenceError:Android 未定义”。那么,如何摆脱这种局面呢?
    猜你喜欢
    • 2021-11-13
    • 2016-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多