Android Chinese characters in WebView

眉间皱痕 提交于 2020-01-25 07:27:10

问题


I have a html code which I saved in home.txt file and placed it raw folder. Now I want to display the same in a WebView. I used the following code for it.

homeWebview = (WebView) findViewById(R.id.homeWebview);
InputStream fileStream = getResources().openRawResource(R.raw.home); 
int fileLen = fileStream.available();

// Read the entire resource into a local byte buffer. 
byte[] fileBuffer = new byte[fileLen]; 
fileStream.read(fileBuffer);

fileStream.close();  
displayText = new String(fileBuffer);

//Display content.          
homeWebview.loadData(displayText, "text/html", "utf-8");

It is working fine. Now I have to display some Chinese characters in the html. I added the Chinese character in home.txt. Here it is the html code:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Language</title>
<style type="text/css">
body {font-family: HelveticaExt-normal, Helvetica, Arial, sans-serif;margin:0;font-size:20px;color:#000000;}
.mainWrapper {margin:0;}
p {margin: 10px;}
p.bodytext {margin: 0 10px 20px;}
.headerText { background:#eeeeee; background: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#e0e0e0));border-top: 2px solid #000000;padding-bottom:7px;}
.headerText p {margin: 10px 10px 0 10px;}
a {color:#324f85;text-decoration:underline;}
.headerbar {border-top:2px solid #000000;border-bottom:2px solid #000000;height:34px;font-family:HelveticaExt-bold, Helvetica, Sans-serif;color:#fff;font-size:18px;padding-left:10px;line-height:34px;margin:0;
 background:-webkit-gradient(linear, left top, left bottom, from(#494e4f), to(#787a7c));
}
.navigationList {list-style-type:none;padding:0;margin:0;}
.navigationList li {height:60px;border-bottom:2px solid #e0e0e0;background-position:10px center;background-repeat:no-repeat;padding-left:60px;line-height:28px;
}
</style>
</head>

<body>
<div class="mainWrapper">
    <div class="headerText">
        <p欢迎您到泰国语言主持人!<a href="http://www.test.com">www.test.com</a> 欲了解更多信息!</p>
    </div>
</div>
</body>

Now it is displaying the common characters well, but all the Chinese char is showing as unknown char. What is the prob in my code?


回答1:


use webView.loadDataWithBaseURL (null, text, "text/html", "utf-8", null);




回答2:


The home.txt file was not in UTF-8 encoded, I open it in notepad++ and change the encoding. Now it is showing properly.




回答3:


I think problem in this line:

displayText = new String(fileBuffer);

You should change to

displayText = new String(fileBuffer, "UTF-8");


来源:https://stackoverflow.com/questions/6196887/android-chinese-characters-in-webview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!