Skip to content Skip to sidebar Skip to footer

Asset Font Is Not Loaded In Android WebView

I'm developing an android activity which is loading an HTML file into a webview. However this acitivty is not loading fonts in some phones e.g. HTC Desire or Sony Xperia Z with 4.

Solution 1:

  • First of all, fonts path should be relative to your HTML/CSS file.

So, instead of this:

@font-face { font-family: 'Persian'; src: url('file:///android_asset/fonts/b_yekan.ttf'); }

Use something like this:

@font-face { font-family: 'Persian'; src: url('fonts/b_yekan.ttf'); }
  • Second, you must make sure that the target you are testing against actually supports Arabic script.

With that, below I am providing a working example.


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 and BLOTUSBD.TTF are downloaded from bornaray.com and stored in assets/fonts/ folder.

loadToWebView(), it is part of a Fragment, hence 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();
    }
}

And the result:

Screenshot

Hope this helps.


Post a Comment for "Asset Font Is Not Loaded In Android WebView"