近期用到WebView加载一些动态的内容的时候遇到一些问题,例如:在加载动态网页时,页面有不少样式表包含一些特殊字符,致使WebView没法识别产生加载异常,程序直接崩溃;另一个就是加载的网页中有图片资源,WebView不识别相对路径,致使图片没法加载。
搜罗了一下网上资料,总结一下,以便后用。
LoadData和loadDataWithBaseURL 的用法;
loadData:
public void loadData (String data, String mimeType, String encoding)
Load the given data into the WebView. This will load the data into WebView using the data: scheme. Content loaded through this mechanism does not have the ability to load content from the network.
Parameters
data mimeType encoding
A String of data in the given encoding. The date must be URI-escaped -- '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
The MIMEType of the data. i.e. text/html, image/jpeg
The encoding of the data. i.e. utf-8, base64
下如API中所说的,
data:是要加载的数据类型,但在数据里面不能出现英文字符:'#', '%', '\' , '?' 这四个字符,若是有的话能够用 %23, %25, %27, %3f,这些字符来替换,在平时测试时,你的数据时,你的数据里含有这些字符,但不会出问题,当出问题时,你能够替换下。
%,会报找不到页面错误,页面全是乱码。乱码样式见符件。
#,会让你的goBack失效,但canGoBAck是可使用的。因而就会产生返回按钮生效,但不能返回的状况。
\ 和? 我在转换时,会报错,由于它会把\看成转义符来使用,若是用两级转义,也不生效,我是对它无语了。
咱们在使用loadData时,就意味着须要把全部的非法字符所有转换掉,这样就会给运行速度带来很大的影响,由于在使用时,在页面stytle中会使用不少%号。页面的数据越多,运行的速度就会越慢。
data中,有人会遇到中文乱码问题,解决办法:参数传"utf-8",页面的编码格式也必须是utf-8,这样编码统一就不会乱了。别的编码我也没有试过。
public
void loadDataWithBaseURL (String baseUrl, String data, String mimeType, String encoding, String historyUrl)
Load the given data into the WebView, use the provided URL as the base URL for the content. The base URL is the URL that represents the page that is loaded through this interface. As such, it is used to resolve any relative URLs. The historyUrl is used for the history entry.
Note for post 1.0. Due to the change in the WebKit, the access to asset files through "file:///android_asset/" for the sub resources is more restricted. If you provide null or empty string as baseUrl, you won't be able to access asset files. If the baseUrl is anything other than http(s)/ftp(s)/about/javascript as scheme, you can access asset files for sub resources.
Parameters
baseUrl data mimeType encoding historyUrl
Url to resolve relative paths with, if null defaults to "about:blank"
A String of data in the given encoding.
The MIMEType of the data. i.e. text/html. If null, defaults to "text/html"
The encoding of the data. i.e. utf-8, us-ascii
URL to use as the history entry. Can be null.
在使用loadDataWithBaseURL时,须要注意的就是 baseUr:虽然API上写的是要传一个Url,但我在用时,发现传一个Url并不能够,我发现这个就是一个标志位,用来标志当前页面的Key值的,而historyUrl就是一个value值,在加载时,它会把baseUrl和historyUrl传到List列表中,看成历史记录来使用,当前进和后退时,它会经过baseUrl来寻找historyUrl的路径来加载historyUrl路径来加载历史界面,须要注意的就是history所指向的必须是一个页面,而且页面存在于SD卡中或程序中(assets),loadDataWithBaseURL,它自己并不会向历史记录中存储数据,要想实现历史记录,须要咱们本身来实现,也许是个人技术有限,我有了比较笨的访求来实现:就是在加载页面时,我把数据另外的写到一个html页面中,并把它保存到SD中,当点击返回时,它会经过historyUrl指向的路径来加载页面,这样就解决了历史记录问题。
前者加载静态网页没有问题,加载远程(WIFI)页面时有些注意,图片加载会出现问题,通常状况下Web页面中给出的是图片相对路径,并无给完整的HTPP路径,这点很重要,须要自行处理一下,否则图片没法正常加载。