android webView中未加载资源字体

时间:2014-08-01 09:30:51

标签: android css fonts webview

我正在开发一个将HTML文件加载到webview中的android活动。
然而,这种活动并不是在某些手机中加载字体,例如HTC Desire或索尼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 /中,就像这样 enter image description here

1 个答案:

答案 0 :(得分:20)

  • 首先,字体路径应该与您的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'); }
  • 第二次,您必须确保您要测试的目标实际上支持阿拉伯语脚本。

有了这个,下面我提供了一个有效的例子。


资产/ 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();
    }
}

结果

Screenshot

希望这有帮助。