简体   繁体   中英

How to set font size and text color in WebView?

I'm developing an Android application in which I have used an HTML file for help contents. I have used a WebView to display the content and every thing is fine. The problem is that user can change the theme and font size of the application. How can I propagate these properties to the content of WebView? Exactly how can I change the font size and text color in WebView? Is there a simple way to do that or I should create different HTMLfiles or CSSes? How to handle the size units (dp, sp, ...)?

I will appreciate your help with this situation.

loadUrl("javascript:(document.body.style.backgroundColor ='red');"); loadUrl("javascript:(document.body.style.fontSize ='20pt');");loadUrl("javascript:(document.body.style.color ='yellow');");

On your android application, use following code to load a web page with user chosen font size and color:

WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new InredisChromeClient(this));
myWebView.setWebViewClient(new InredisWebViewClient(this));
myWebView.clearCache(true);
myWebView.clearHistory();
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.loadUrl("http://demo.com/content.html?font-size=12&fontcolor=blue");

On the content.html page, enable JavaScript and use jQuery and its function as below:

function getCssValue(sCSS)
{
    var sPageURL = window.location.search.substring(1);
    var sValues = sPageURL.split('&');
    for (var i = 0; i < sValues.length; i++) 
   {
       var sPair = sValues[i].split('=');
       if (sPair[0] == sCSS) 
       {
           return sPair[1];
        }
   }
}        

$(document).ready(function(){
    // Set the Font Size from URL
    $('html').css('font-size', getCssValue('font-size'));
 });

It is best to do theme activities using CSS and Javascript. However if we want to pass on some settings from Android to the WebView dynamically, it is possible and a solution is to use the JavascriptInterface . Here is one way of doing it:

Firstly, we define a class which will be used as a bridge between the Android app and the WebView for JS interactions.

Here WebInterface is an inner class in the Activity and hence it has direct access to myWebView, which is a WebView instance variable.

        public class WebInterface {
        private Activity activity;

        public WebInterface(Activity activiy) {
            this.activity = activiy;
        }


        @JavascriptInterface
        public void changeTheme() {

            activity.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // All of the theme settings could go here, the settings passed on by Android
                    myWebView.loadUrl("javascript:document.body.style.backgroundColor ='red';");
                    myWebView.loadUrl("javascript:document.body.style.fontSize ='20pt'");
                    myWebView.loadUrl("javascript:document.body.style.color ='yellow';");

                    //OR load your data as shown here http://stackoverflow.com/a/7736654/891092

                    htmlData = "<link rel=\"stylesheet\" type=\"text/css\" href=\"theme.css\" />" + htmlData;
                    // lets assume we have /assets/theme.css file
                    myWebView.loadDataWithBaseURL("file:///android_asset/", htmlData, "text/html", "UTF-8", null);
                }
            });
        }
    }

Note that it is very important to run your code in UI Thread otherwise it will not work.

Here is how the Activity registers the WebView with the JavascriptInterface:

myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(jsInterface, "JSInterface");

In the HTML file, which the user is viewing, a button or widget could be made to change theme by calling code in Android through the bridge:

<input type="button" value="Say hello" onClick="doChangeTest()" />
<script type="text/javascript">
    function doChangeTest(){
        JSInterface.changeTheme(); // this calls the changeTheme in WebInterface
    }

</script>

First you need to define a webView and after that use below method.

  1. lightFont is your font that you should store in asset folder.

  2. color is your text color.

  3. font size : you can change font size.(for example 20px or medium and etc).

  4. at the end you need to use seconde method to show html on webView

First Method:

 public static String getStyledFont(String html) {


        boolean addBodyStart = !html.toLowerCase().contains("<body>");
        boolean addBodyEnd = !html.toLowerCase().contains("</body");
        return "<style type=\"text/css\">" +
                "@font-face {font-family: CustomFont;" +
                "src: url(\"file:///android_asset/lightFont.ttf\")}" +
                "body {color: #787878;}"+
                "body {font-family: CustomFont;font-size: x-small;}</style>" +
                (addBodyStart ? "<body>" : "") + html +(addBodyEnd ? "</body>" : "");
    }

Second method:

String htmlText = getStyledFont(yourText);
        webView.loadDataWithBaseURL("file:///android_asset/",
                htmlText ,
                "text/html; charset=UTF-8", null, null);

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