简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM