Google webfonts not working using Web View in Android 4.0 and 4.2.2


Answers

WebView in Android 4.0.X does not support web fonts

Question

When using Google web fonts in my Android app that uses web view they work fine in version 4.4 of Android. Some devices with Android 4.2 show the default font, most work correctly. On Android 4.0 however all fonts default to the same default font.

Because we like to target Android 4.0 and higher with our app I am looking for a way to get the Google web fonts working reliably.

The app does little more than opening html files from a server in the web view.

Update: It turns out that some Android 4.2.2 devices do not show Google web fonts correctly. It is not clear what makes these devices stand out from the ones that I tested and where web fonts work correctly.

What can I do to make web fonts work reliably over different Android versions and devices?




Even simpler, you can use the Asset URL format to reference the font. No programming needed!

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

body { 
   font-family: 'myface', serif;

...




How to change font face of Webview in Android?

There's a working example of this in this project. It boils down to:

  1. In your assets/fonts folder, place the desired OTF or TTF font (here MyFont.otf)
  2. Create a HTML file that you'll use for the WebView's content, inside the assets folder (here inside assets/demo/my_page.html):

    <html>
    <head>
    <style type="text/css">
    @font-face {
        font-family: MyFont;
        src: url("file:///android_asset/fonts/MyFont.otf")
    }
    body {
        font-family: MyFont;
        font-size: medium;
        text-align: justify;
    }
    </style>
    </head>
    <body>
    Your text can go here! Your text can go here! Your text can go here!
    </body>
    </html>
  3. Load the HTML into the WebView from code:

    webview.loadUrl("file:///android_asset/demo/my_page.html");

Take note that injecting the HTML through loadData() is not permitted. As per the documentation:

Note that JavaScript's same origin policy means that script running in a page loaded using this method will be unable to access content loaded using any scheme other than 'data', including 'http(s)'. To avoid this restriction, use loadDataWithBaseURL() with an appropriate base URL.

As @JaakL suggests in the comment below, for loading HTML from a string, you should instead provide the base URL pointing to your assets:

webView.loadDataWithBaseURL("file:///android_asset/", htmlData);

When referencing the font in htmlData, you may then simply use /fonts/MyFont.otf (omitting the base URL).




Links



Tags