android webview loaddata addheader,Android系统。 WebView和loadData

WebView.loadData() is not working properly at all. What I had to do was:

String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";

myWebView.loadData(header+myHtmlString, "text/html", "UTF-8");

I think in your case you should replace UTF-8 with latin1 or ISO-8859-1 both in header and in WebView.loadData().

And, to give a full answer, here is the official list of encodings: http://www.iana.org/assignments/character-sets

I update my answer to be more inclusive:

To use WebView.loadData() with non latin1 encodings you have to encode html content. Previous example was not correctly working in Android 4+, so I have modified it to look as follows:

WebSettings settings = myWebView.getSettings();

settings.setDefaultTextEncodingName("utf-8");

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {

String base64 = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);

myWebView.loadData(base64, "text/html; charset=utf-8", "base64");

} else {

String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";

myWebView.loadData(header + htmlString, "text/html; charset=UTF-8", null);

}

But later I have switched to WebView.loadDataWithBaseURL() and the code became very clean and not depending on Android version:

WebSettings settings = myWebView.getSettings();

settings.setDefaultTextEncodingName("utf-8");

myWebView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);

For some reason these functions have completely different implementation.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值