How to change font face of Webview in Android?

前端 未结 14 1133
北荒
北荒 2020-11-22 12:23

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 cus

14条回答
  •  孤街浪徒
    2020-11-22 12:49

    Many of the above answers work lie a charm if you have your content in your assets folder.

    However, if you like me want to download and save all your assets from a server to your internal storage you can instead use loadDataWithBaseURL and use a reference to your internal storage as the baseUrl. Then all files there will be relative to the loaded html and are found and used correctly.

    In my internal storage I have saved the following files:

    • IndigoAntiqua2Text-Regular.ttf
    • style.css
    • image.png

    Then I use the following code:

    WebView web = (WebView)findViewById(R.id.webby);
    //For avoiding a weird error message
    web.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    
    String webContent = ""
                                + "
    I am a text rendered with INDIGO
    "; String internalFilePath = "file://" + getFilesDir().getAbsolutePath() + "/"; web.loadDataWithBaseURL(internalFilePath, webContent, "text/html", "UTF-8", "");

    The CSS file used in the above html (style.css):

    @font-face {
      font-family: 'MyCustomRunning';
      src: url('IndigoAntiqua2Text-Regular.ttf')  format('truetype');
    }
    
    .running{
        color: #565656;
         font-family: "MyCustomRunning";
         font-size: 48px;
    }
    

    I have only tried this while targeting minSdkVersion 19 (4.4) so I have no idea if it works on other versions

提交回复
热议问题