Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
242 views
in Technique[技术] by (71.8m points)

How to change font face of Webview in Android?

I want change the default font of webview to a custom font. I'm using webview in developing an bilingual browser app for Android.

I tried getting an instance of custom typeface by placing my custom font in assets. But still couldn't set webview's default font to my font.

This is what I tried:

Typeface font = Typeface.createFromAsset(getAssets(), "myfont.ttf"); 
private WebView webview;
WebSettings webSettings = webView.getSettings();
webSettings.setFixedFontFamily(font);

Can anyone correct this or suggest any other method to change webview's default font to a custom font?

Thanks!

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...