【问题标题】:android How do I use custom font to remote html in webView?android 如何在webView中使用自定义字体来远程html?
【发布时间】:2021-02-18 22:43:48
【问题描述】:

当我将 assets/font 中的自定义字体应用到本地 html 时。 我只是像下面这样设置字体 @font-face { 字体家族:‘我的’字体; src: url('file:///android_asset/fonts/my'font); } 但是,当我使用 loadUrl(“remote html url”) 时,上面的代码不起作用。 有个好主意吗?

以下链接显示本地字体和本地 html 的示例代码。 How to change font face of Webview in Android?

但是我需要远程 html 和本地字体示例。

【问题讨论】:

标签: android webview


【解决方案1】:

使用 jsoup 处理字体


您好先生,您可以使用 jsoup 处理您的 webview

首先你需要实现jsoup implementation 'org.jsoup:jsoup:1.11.1'

那么您需要像这样获取您的网站 Document doc = Jsoup.connect("http://youramazing.site").get();

之后,您可以使用 append 方法将自定义样式添加到文档中

        doc.head().append(" <style>\n" +
                "            @font-face {\n" +
                "            font-family: 'Roboto Slab Bold';\n" +
                "            src: url('file:///android_asset/fonts/syne.ttf')\n" +
                "            }\n" +
                "            body { font-family: 'Roboto Slab Bold', serif; font-size: 17px; color: #000; }\n" +
                "            a { color: #000; }\n" +
                " </style>");

之后,您可以使用 webview 处理它 String s = doc.html() webView.loadData(s,"text/html","utf-8");

带有 AsyncTask 的完整代码:

public class MainActivity extends AppCompatActivity {
    WebView webView;
    Document doc;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webView = findViewById(R.id.wewewew);
        AsyncTask<Void,Void,String> asyncTask = new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... voids) {
                try {
                    doc = Jsoup.connect("http://youramazing.site/").get();
                } catch (IOException e) {
                    e.printStackTrace();
                }


                doc.head().append(" <style>\n" +
                        "            @font-face {\n" +
                        "            font-family: 'Roboto Slab Bold';\n" +
                        "            src: url('file:///android_asset/fonts/syne.ttf')\n" +
                        "            }\n" +
                        "            body { font-family: 'Roboto Slab Bold', serif; font-size: 17px; color: #000; }\n" +
                        "            a { color: #000; }\n" +
                        " </style>");
                return doc.html();
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                webView.setWebViewClient(new WebViewClient());
                webView.loadData(s,"text/html","utf-8");
            }
        };
        asyncTask.execute();



    }
}

【讨论】:

    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    • 1970-01-01
    • 2013-07-14
    相关资源
    最近更新 更多