如何在Android中自定义WebView



我想从json加载数据到WebView !对于这项工作,我应该使用自定义webView !如:自定义字体,背景,方向和更多…

我为自定义webView编写以下代码:

    String style = "@font-face {font-family: "MyFont";src: url('file:///android_asset/fonts/iran_sans_mobile.ttf');} " +
            "body {background:#FFFFFF;} div,h1,h2,p,h3 { font-family:"MyFont";line-height:30px;  " +
            "text-align: justify; color: #2d2d2d ;direction: rtl}";

并且此代码已将内容设置为webview:

 if (content != null) {
            post_content_web.getSettings().setJavaScriptEnabled(true);
            WebSettings settings = post_content_web.getSettings();
            settings.setDefaultTextEncodingName("utf-8");
            String style = "@font-face {font-family: "MyFont";src: url('file:///android_asset/fonts/iran_sans_mobile.ttf');} " +
                    "body {background:#FFFFFF;} div,h1,h2,p,h3 { font-family:"MyFont";line-height:30px;  " +
                    "text-align: justify; color: #2d2d2d ;direction: rtl}";
            post_content_web.loadData(content, "text/html; charset=utf-8", "utf-8");
        }

但我不知道如何设置这个自定义到我的webview !

如何将此自定义设置为webview ?3

设置WebViewClient监听页面加载事件,并注入你的css样式代码:

...
String style = "@font-face {font-family: "MyFont";src: url('file:///android_asset/fonts/iran_sans_mobile.ttf');} " +
                    "body {background:#FFFFFF;} div,h1,h2,p,h3 { font-family:"MyFont";line-height:30px;  " +
                    "text-align: justify; color: #2d2d2d ;direction: rtl}";
post_content_web.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url) {
        // Inject CSS
        post_content_web.loadUrl("javascript:(function() {" +
                "var parent = document.getElementsByTagName('head').item(0);" +
                "var style = document.createElement('style');" +
                "style.type = 'text/css';" +
                "style.innerHTML = " + style + ";" +
                "parent.appendChild(style)" +
                "})()");
        super.onPageFinished(view, url);
    }
});
post_content_web.loadData(content, "text/html; charset=utf-8", "utf-8");
...

试试这个代码:

if (content != null) {
    post_content_web.getSettings().setJavaScriptEnabled(true);
    WebSettings settings = post_content_web.getSettings();
    settings.setDefaultTextEncodingName("utf-8");
    String myCustomStyleString = "<style type="text/css">@font-face {font-family: MyFont;src: " +
            "url("file:///android_asset/fonts/iran_sans_mobile.ttf")}body,* {font-family: MyFont; font-size: " +
            "medium;text-align: justify;}</style>";
    post_content_web.loadDataWithBaseURL("", myCustomStyleString + "<div style="direction:rtl">"
            + content + "</div>", "text/html", "utf-8", null);
}

最新更新