我正在开发一个将 HTML 文件加载到 Web View 中的 Android Activity 。
但是,此 Activity 并未在某些手机中加载字体,例如HTC Desire 或 Sony Xperia Z 与 4.4 或 4.1 机器人。
我想知道我是否遗漏了什么,或者这仅取决于我正在测试我的应用程序的手机。
private void loadToWebView(String s) {
try {
pageWebView.loadDataWithBaseURL("file:///android_asset/", s,
"text/html", "utf-8", null);
configureWebView(pageWebView);
} catch (Exception e) {
e.printStackTrace();
}
}
这是 html 标题:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<style type="text/css">
@font-face { font-family: 'Persian'; src: url('file:///android_asset/fonts/b_yekan.ttf'); }
@font-face { font-family: 'Persian2'; src: url('file:///android_asset/fonts/b_homa.ttf'); }
@font-face { font-family: 'PersianTitle'; src: url('file:///android_asset/fonts/b_titr.ttf');}
body {font-family: 'Persian';}
h1 {font-family: 'PersianTitle';}
h2 {font-family: 'Persian2';}
</style>
字体像这样位于assets/fonts/中
最佳答案
- 首先,字体路径应与您的 HTML/CSS 文件相关。
所以,而不是这个:
@font-face { font-family: 'Persian'; src: url('file:///android_asset/fonts/b_yekan.ttf'); }
使用这样的东西:
@font-face { font-family: 'Persian'; src: url('fonts/b_yekan.ttf'); }
- 其次,您必须确保您测试的目标确实支持阿拉伯文字。
有了这个,下面我提供了一个工作示例。
assets/about_us.html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<style type="text/css">
@font-face { font-family: 'B Homa'; src: url('fonts/BHOMA.TTF');}
@font-face { font-family: 'B Lotus'; src: url('fonts/BLOTUS.TTF');}
@font-face { font-family: 'B Lotus Bold'; src: url('fonts/BLOTUSBD.TTF');}
</style>
</head>
<body>
<p style="font-family:'B Homa';font-size:20px;">B Homa: مخصص</p>
<p style="font-family:'B Lotus';font-size:20px;">B Lotus: مخصص</p>
<p style="font-family:'B Lotus Bold';font-size:20px;">B Lotus Bold: مخصص</p>
</body>
</html>
BHOMA.TTF、BLOTUS.TTF 和BLOTUSBD.TTF 从bornaray.com 下载。并存储在 assets/fonts/
文件夹中。
loadToWebView(),它是 Fragment
的一部分,因此 getActivity().getAssets()
:
private void loadToWebView() {
AssetManager assetManager = getActivity().getAssets();
try {
InputStream input = assetManager.open("about_us.html");
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
mWebView.loadDataWithBaseURL("file:///android_asset/",
new String(buffer), "text/html", "UTF-8", null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
结果:
希望这对您有所帮助。
关于android - Android webView 中未加载 Assets 字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25077094/