简体   繁体   English

如何从Web视图中的资产html文件正确加载字符串

[英]How to load correctly a string from asset html file in a webview

I have an html file in asset folder and i would like to load it in a webview. 我在资产文件夹中有一个html文件,我想将其加载到webview中。 I would like to use the string, and not the file in order to replace the content of file when i want (keep only one file and change the content i want to display). 我想使用字符串而不是文件,以便在需要时替换文件的内容(仅保留一个文件并更改我要显示的内容)。 For example my html file is like this: 例如我的html文件是这样的:

<!DOCTYPE html>
<html>
<head>
    <title>This is demo</title>
</head>
<body>

<p data-height="265" data-theme-id="0" data-slug-hash="dYPxYp" data-default-tab="html,result" data-user="sckarolos" data-embed-version="2" data-pen-title="SVG Shape Example" class="codepen">
    See the Pen <a href="https://codepen.io/sckarolos/pen/dYPxYp/">SVG Shape Example</a>
    by sckarolos (<a href="https://codepen.io/sckarolos">@sckarolos</a>) on <a href="https://codepen.io">CodePen</a>.</p>
<script async src="https://production-assets.codepen.io/assets/embed/ei.js"></script>


</body>
</html>

I have these two methods for reading the html file from assets as string and load it in a webview: 我有以下两种方法可从资产中以字符串形式读取html文件并将其加载到webview中:

private String getHtmlFromAsset() {
        InputStream is;
        StringBuilder builder = new StringBuilder();
        String htmlString = null;
        try {
            is = getAssets().open(htmlFilename);
            if (is != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                }

                htmlString = builder.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return htmlString;
    }

    /**
     * Loads html page with the content.
     */
    private void loadHtmlPage(WebView webView) {
        String htmlString = getHtmlFromAsset();
        if (htmlString != null) {
            webView.loadDataWithBaseURL(null, htmlString, "text/html", "UTF-8", null);
        }
        else
            Toast.makeText(this, "No such page", Toast.LENGTH_LONG).show();
    }     

And in my activity i use webview like this: 在我的活动中,我使用webview像这样:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        AssetManager assetManager = getAssets();

         //try to display html content
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setAllowFileAccess(true);
        webView.getSettings().setAllowFileAccessFromFileURLs(true);
        webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        loadHtmlPage(webView);
      }     

On debuging i can see that my file read successfully and my string has the content of html file. 在调试时,我可以看到我的文件已成功读取,并且我的字符串具有html文件的内容。 But when i am trying load it in webview, the result is nothing. 但是,当我尝试将其加载到webview中时,结果什么也没有。 If i try to load the local html file using this: 如果我尝试使用此方法加载本地html文件:

webView.loadUrl("file:///android_asset/myFile.html");   

then the file loads and displays successfully. 然后文件加载并成功显示。 I suppose that my fault is in the way i use the string that i take back from getHtmlFromAsset and pass in loadHtmlPage. 我想我的错在于我使用从getHtmlFromAsset取回并传入loadHtmlPage的字符串的方式。

Any help will be appreciated. 任何帮助将不胜感激。

Here, code pan required javascript access so when link load you need to provide javascript access. 在这里,代码平移需要javascript访问,因此当链接加载时,您需要提供javascript访问。 this is working code also check into my emulator. 这是工作代码,也请检查我的模拟器。 Also, don't forget to give internet permission on the manifest. 另外,不要忘记在清单上授予Internet许可。

XML: XML:

<WebView
    android:id="@+id/wv"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

JAVA: JAVA:

String str = "<!DOCTYPE html>\n" +
        "<html>\n" +
        "<head>\n" +
        "    <title>This is demo</title>\n" +
        "</head>\n" +
        "<body>\n" +
        "\n" +
        "<p data-height=\"265\" data-theme-id=\"0\" data-slug-hash=\"dYPxYp\" data-default-tab=\"html,result\" data-user=\"sckarolos\" data-embed-version=\"2\" data-pen-title=\"SVG Shape Example\" class=\"codepen\">\n" +
        "    See the Pen <a href=\"https://codepen.io/sckarolos/pen/dYPxYp/\">SVG Shape Example</a>\n" +
        "    by sckarolos (<a href=\"https://codepen.io/sckarolos\">@sckarolos</a>) on <a href=\"https://codepen.io\">CodePen</a>.</p>\n" +
        "<script async src=\"https://production-assets.codepen.io/assets/embed/ei.js\"></script>\n" +
        "\n" +
        "\n" +
        "</body>\n" +
        "</html>";
WebView wv = findViewById(R.id.wv);
wv.setWebViewClient(new WebViewClient() {
    public boolean shouldOverrideUrlLoading(WebView view, String url){
        // do your handling codes here, which url is the requested url
        view.getSettings().setJavaScriptEnabled(true);
        view.loadUrl(url);
        return false; // then it is not handled by default action
    }
});
wv.loadData(str, "text/html", "UTF-8");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM