简体   繁体   English

如何在WebView中设置字体大小和文本颜色?

[英]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. 我正在开发一个Android应用程序,其中使用了HTML文件作为帮助内容。 I have used a WebView to display the content and every thing is fine. 我已经使用WebView来显示内容,并且一切都很好。 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? 如何将这些属性传播到WebView的内容? Exactly how can I change the font size and text color in WebView? 究竟该如何在WebView中更改字体大小和文本颜色? Is there a simple way to do that or I should create different HTMLfiles or CSSes? 有没有简单的方法可以做到这一点,或者我应该创建不同的HTMLfile或CSS? How to handle the size units (dp, sp, ...)? 如何处理尺寸单位(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: 在您的android应用程序上,使用以下代码加载用户选择的字体大小和颜色的网页:

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: 在content.html页面上,启用JavaScript并使用jQuery及其功能,如下所示:

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. 最好使用CSS和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 . 但是,如果我们想将某些设置从Android动态传递到WebView,则可以实现,并且解决方案是使用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. 首先,我们定义一个类,该类将用作android应用程序和WebView进行JS交互的桥梁。

Here WebInterface is an inner class in the Activity and hence it has direct access to myWebView, which is a WebView instance variable. 这里的WebInterface是Activity中的一个内部类,因此可以直接访问myWebView,这是一个WebView实例变量。

        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. 请注意,在UI Thread中运行代码非常重要,否则它将无法正常工作。

Here is how the Activity registers the WebView with the JavascriptInterface: 这是Activity通过JavascriptInterface注册WebView的方式:

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: 在用户正在查看的HTML文件中,可以通过通过桥在Android中调用代码来制作按钮或小部件来更改主题:

<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. 首先,您需要定义一个webView ,然后使用下面的方法。

  1. lightFont is your font that you should store in asset folder. lightFont是您应存储在资产文件夹中的字体。

  2. color is your text color. color是您的文字颜色。

  3. font size : you can change font size.(for example 20px or medium and etc). font size :您可以更改字体大小。(例如20px或中号等)。

  4. at the end you need to use seconde method to show html on webView 最后,您需要使用seconde方法在webView上显示html

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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