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

How to set font size and text color in WebView?

我正在开发一个 Android 应用程序,我在其中使用了一个 HTML 文件作为帮助内容。我使用 WebView 来显示内容,一切都很好。 问题是用户可以更改应用程序的主题和字体大小。如何将这些属性传播到 WebView 的内容?究竟如何更改 WebView 中的字体大小和文本颜色?有没有一种简单的方法可以做到这一点,或者我应该创建不同的 HTML 文件或 CSS?如何处理尺寸单位(dp、sp、...)?

我将感谢你对这种情况的帮助。

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

在您的 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");

在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'));
 });

最好使用CSS和Javascript进行主题活动。但是,如果我们想将一些设置从 Android 动态传递到 WebView,这是可能的,解决方案是使用 JavascriptInterface。这是一种方法:

首先,我们定义一个class,它将用作Android应用程序和WebView之间的桥梁,用于JS交互。

这里的 WebInterface 是 Activity 中的一个内部 class,因此它可以直接访问 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 

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

请注意,运行 您的代码在 UI 线程中非常重要,否则将无法运行。

下面是 Activity 向 Javascript 接口注册 WebView 的方式:

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

在用户正在查看的 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>

首先你需要定义一个webView,然后使用下面的方法。

  1. lightFont 是您应该存储在资产文件夹中的字体。

  2. color 是你的文字颜色。

  3. font size : 您可以更改字体大小。(例如 20px 或 medium 等)。

  4. 最后你需要使用 seconde 方法在 webView

  5. 上显示 html

第一种方法:

 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>" : "");
    }

第二种方法:

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