Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set WebView font

I'm trying to set the html of my WebView to as;

    "<html>" +
        "<head>" +
            "<meta http-equiv=\"content-type\" content=\"text/html;\" charset=\"UTF-8\">" +
            "<style type=\"text/css\">" +
                "@font-face {" +
                        "font-family: 'SourceSansPro Regular'; " +
                        "src: url('file:///android_asset/fonts/SourceSansPro-Regular.ttf' +
                        // "/android_asset/fonts
                        "/SourceSansPro-Regular.ttf');" +
                    "} " +
                "body {" +
                    "font-family: 'SourceSansPro Regular';" +
                    // "color:f00;" +
                "}" +
            "</style> " +
        "</head> " +
        "<body>" +
            " My Html Data"+
        "</body>" +
    "</html>";

But font is not being applied. The font applied well if I create an html file in assets folder. But I need to set body dynamically so can't use this way.

like image 648
Ammar Avatar asked Feb 15 '26 23:02

Ammar


1 Answers

Using webview websettings you can set your default font family for webview

WebSettings webSettings = myWebView.getSettings();
webSettings.setStandardFontFamily("Roboto-Light");

//if it is a system font else parse the font family from asset or from style as follows,

int[] attrs = { android.R.attr.fontFamily };
        TypedArray a = obtainStyledAttributes(R.style.myFontStyle, attrs);
        String fontfamily = a.getString(0);

        // Main
        webSettings.setStandardFontFamily(fontfamily);

Note : Even if you use this API : setStandardFontFamily to specify the font family webview will give the priority to font which is coming from server(html page)

eg:

  1. if html page not specified any font then it will take this dynamic font family.

    2.html specified font is not available then it will take our dynamic font in webview

Other than this Priority is given for serverpage font family not a dynamic.

like image 120
Muthuraj Avatar answered Feb 18 '26 11:02

Muthuraj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!