Examples of how Android WebView loads HTML, CSS and other languages

preface

This topic may not be very good. I haven't come up with a more suitable one for a long time. When developing WebView on Android, sometimes the background does not necessarily give you a URL, but gives you some HTML, CSS and JS language codes, and then you assemble the language that WebView can recognize and load it into the page.

There are three ways to load HTML: first, the HTML file stored in the assets folder; 2、 Directly load a specified web page. 3、 The HTML code parsed from the network. Note that here is the code, that is, the string format.

Example

If the background gives you a URL, and the URL is actually the connection corresponding to JSON data and cannot be directly loaded into WebView, how to solve it at this time. I can say that I met this problem a year ago. Later, I didn't know how to check it. I didn't find the corresponding information on the Internet. Secondly, I didn't have front-end people around to guide me. Today, I asked my front-end colleagues before I understood one or two.

code analysis

In the usual front-end development, they usually write their own HTML and CSS code, and then display it in the browser, that is, the WebView in Android. In the case of Android, you can only splice code. The background provides the corresponding code, and Android develops its own splicing. In fact, it is not so difficult as expected, because in the final analysis, it is a string. A certain formatting of the string can easily achieve the effect.

code implementation

This is a tool class, which is specially used to connect HTML, CSS and other languages into HTML. Let's take a look at the method createhtmldata we use, which returns a string connected by string. The concat method is as follows:

CSS: take out the CSS code in JSON and prefix it

HIDE_ HEADER_ Style: defines the style of the overall HTML

HTML: This is the HTML code in the JSON data directly

JS: take out the JS code in JSON and prefix it.

Adding tag prefix is to use string. Format (needed_format_js_tag, URL); Method to replace the% s in the previous format with the following code.

Reference to WebView

Source code reference: https://github.com/yiyibb/Zhihu

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>