WebView(Android)中的字符集 [英] Character set in WebView (Android)

查看:75
本文介绍了WebView(Android)中的字符集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用loadData()方法在WebView中显示Java字符串中的一些数据:

I am trying to display some data from a Java String in a WebView, using the loadData() method:

wv.loadData(myString, "text/html, "utf-8");

我遇到的问题是WebView破坏了非ASCII(我假设吗?)字符的输出.如果我使用TextView而不是WebView,则不会发生此问题,并且文本可以正确显示(尽管涉及一些HTML标记,所以最终不希望使用TextView).

The issue I am having is that the WebView mangles the output of non-ASCII (I assume?) characters. If I use a TextView instead of a WebView, this problem does not occur, and the text displays correctly (although there is some HTML markup involved, so a TextView is not ultimately desirable).

如果有帮助,当我运行以下代码时:

If it helps, when I run the following code:

for(int i = 0; i < myString.length() && i < 400; i++)
      Log.i("Text", myString.charAt(i) + ": " + (int) myString.charAt(i));

在日志中会出现这样的冒犯字符:

an offending character appears as such in the log:

05-27 13:15:45.110:INFO/Text(606):â:8217

05-27 13:15:45.110: INFO/Text(606): â: 8217

我认为这是一个字符集问题,但是我不太确定如何解决它.

This is a character set issue, I think, but I'm not quite sure how to resolve it.

这是HTML的摘要(我不确定我的雇主是否允许内容的完整发布):

Here's a snippet of the HTML (I'm not sure if my employer would allow a full posting of the content):

突尼斯总理

引起问题的是字符.注意:我要显示的不是完整的HTML页面.如果有问题,则只是带有HTML标记的文本.

It is the ’ character that is causing issue. NB: What I'm displaying is not a fully-formed HTML page.. just text with HTML markup, if that matters..

推荐答案

我有一个类似的问题,在WebView中,我传递给loadData()方法的字符串没有正确显示(用奇数字符代替了正确的字符)DBCS的).就我而言,该字符串已使用UTF-8正确编码,问题在于loadData()如何使用该字符串.

I had a similar problem, where the string I was passing into the loadData() method was not being presented properly in the WebView (had odd characters instead of correct DBCS ones). In my case, the string was properly encoded in UTF-8 and the problem was in how loadData() was using the string.

我发现在mime类型参数而不是encoding参数中指定字符集很重要.具体来说,通话必须是

I found that is important to specify the character set within the mime type argument, and not the encoding argument. Specifically the call had to be

wv.loadData(myString, "text/html; charset=utf-8", encoding);

就我而言,我将null用作编码变量,并且它可以正常工作(Android 4.2.1).阅读关于loadData()的API文档;它似乎表明它将接受"base64",而所有其他值将导致data参数被视为URL编码的ASCII.

In my case, I passed null as the encoding variable and it worked (Android 4.2.1). Reading the API documentation on loadData(); it seems to indicate that it will accept "base64" and all other values will cause the data argument to be treated as URL-encoded ASCII.

因此,您不能使用encoding参数设置字符串的编码,必须在mime类型中指定编码.

Therefore, you CANNOT set the encoding of the string with the encoding parameter, you must specify the encoding in the mime type.

这篇关于WebView(Android)中的字符集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆