1

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.

Raha
  • 35
  • 2
  • 4
  • A WebView is a Web browser. It's meant to show (X)HTML contents or navigate. Its contents aren't part of the UI. – Phantômaxx Feb 07 '15 at 09:30
  • Thank you. I know that, but what about default settings for contents which have not any style? And what's the reason of methods like setDefaultFontSize(), setTextZoom() and deprecated setTextSize()? – Raha Feb 07 '15 at 09:49
  • for `default settings for contents which have not any style?` use a CSS file. `setDefaultFontSize()` sets the font size in sp. `setTextZoom()` sets the zoom level in %. For the deprecated `setTextSize()`, see: http://developer.android.com/reference/android/webkit/WebSettings.TextSize.html – Phantômaxx Feb 07 '15 at 09:54

4 Answers4

1

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

Sunit Kumar Gupta
  • 1,203
  • 1
  • 11
  • 19
1

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'));
 });
Francis Au
  • 56
  • 4
  • Thanks a lot for your straight solution. This method works well in browser. But is not working in the application. When I enable the JavaScript I get the white page and disabling it cause ignoring formatting properties. This is how I tried to display the page. Did I forget something? myWebView.getSettings().setJavaScriptEnabled(true); myWebView.loadUrl("file:///android_asset/help.html?font-size=12&fontcolor=880088"); – Raha Feb 07 '15 at 22:11
  • Please help to check if the updated WebView code works for your case. – Francis Au Feb 09 '15 at 14:03
0

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>
ZakiMak
  • 2,072
  • 2
  • 17
  • 26
  • Thank you for your help. I have little experience with JavaScript but if I understood well, in this approach user should change the theme in the HTML content. But in my case the theme is defined in the application and what I want to do is changing the size and color of HTML content according to the current theme. – Raha Feb 07 '15 at 22:04
  • I added more info in the code. It's possible to also load CSS file from your app based on some condition. However having html content will make things easier for you. Please check the answer. – ZakiMak Feb 08 '15 at 06:17
0

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);
roy
  • 6,685
  • 3
  • 26
  • 39
nima barati
  • 345
  • 3
  • 8