3

我正在尝试编写一个执行简单toast. 当我尝试HTMLtoast. 但是当我将相同的script代码放在文件assert夹(script.js)下的单独文件中时,它无法注入javascript.

我支持 API 15 及更高版本。

这是代码,我尝试在其中注入script.

    myWebView = (WebView) findViewById(R.id.webviewid);

    myWebView.loadDataWithBaseURL("file:///android_asset/",
            "<html>" +
            "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">" +
            "<style type=\"text/css\">\n" +
            "@font-face {\n" +
            "    font-family: MyFont;\n" +
            "    src: url(\"file:///android_asset/fonts/myfont.ttf\")\n" +
            "}\n" +
            "body {\n" +
            "    font-family: MyFont;\n" +
            "    font-size: medium;\n" +
            "    text-align: justify;\n" +
            "}\n" +
            "</style>" +
            "</head>" +
            "<body>" +
            "<input type=\"button\" value=\"Say hello\" onClick=\"showAndroidToast('Hello Android!')\" />" +
            "<script type=\"text/javascript\" src=\"file:///android_asset/www/js/script.js\"/>" +
            "</body>" +
            "</html>", "text/html", "UTF-8", null);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    myWebView.setWebViewClient(new MyWebViewClient());

这是我的javascript代码。(脚本.js)

    function showAndroidToast(toast) {
        Android.showToast(toast);
    };

这是我的Javascript界面:

    protected 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();
        }
    }

如何注入javascript文件?任何帮助表示赞赏。

我的项目结构是这样的:

    ---
      |
      ---- App
           |
           -----src
                |
                -----main
                     |
                     ------asserts
                     |     |
                     |     ------fonts
                     |     |
                     |     ------www
                     |     |     |
                     |     |     ------js
                     |     |           |
                     |     |           ------script.js
                     |
                     ------java
                     |
                     ------res

猫日志显示:

 E/Web Console﹕ Uncaught ReferenceError: showAndroidToast is not defined:13
4

1 回答 1

0

由于您使用 WebView 来显示数据,您可以将其上传到服务器甚至 Dropbox,然后通过 url 导入连接它?

于 2014-09-24T13:46:49.293 回答