Android   发布时间:2022-04-28  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了在Android中使用来自res / font的自定义字体与WebView大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想改变加载到WebView中的html字符串的字体,就像这个问题中提到的一样:

How to change font face of Webview in Android?

区别在于我没有使用旧方法将字体文件存储在assets文件夹中,但我将它们存储在res / font中,如“字体在XML中”android字体支持文档中所述:

https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html

现在,我显然不能使用:

文件:///android_asset/fonts/my_font.otf

我试过了

文件:///android_res/font/my_font.otf

以及在res / font文件夹中描述我的字体路径的许多其他方法,但它们都不起作用.

如果我的字体存储在res / font文件夹中,如何为加载html字符串的WebView使用自定义字体系列?

//编辑:

我当前的实现不起作用是:

@BindingAdapter("loadData")
public static void loadData(WebView webView,String htmlData) {
    webView.loadDataWithBaseURL(null,htmlData,"text/html","utf-8",null);
}

@BindingAdapter({"loadData","fontFamily"})
public static void loadData(WebView webView,String htmlData,@FontRes int fontFamilyId) {
    TypedValue value = new TypedValue();
    ApplicationActivity.getSharedApplication().getresources().getValue(fontFamilyId,value,truE);
    String fontPath = value.String.toString();
    File fontFile = new File(fontPath);

    String prefix = "<html>\n"
            +"\t<head>\n"
            +"\t\t<style type=\"text/css\">\n"
            +"\t\t\t@font-face {\n"
            +"\t\t\t\tfont-family: 'CustomFont';\n"
            +"\t\t\t\tsrc: url(\"file:///android_res/font/"+fontFile.getName()+"\")\n"
            +"\t\t\t}\n"
            +"\t\t\tbody {\n"
            +"\t\t\t\tfont-family: 'CustomFont';\n"
            +"\t\t\t}\n"
            +"\t\t</style>\n"
            +"\t</head>\n"
            +"\t<body>\n";
    String postfix = "\t</body>\n</html>";

    loadData(webView,prefix + htmlData + postfiX);
}

解决方法

刚试过,这与从资源加载字体的工作方式类似,你只需要改变基本网址来指向资源.

示例HTML

<html>
<head>
    <style>
        @font-face {
            font-family: 'CustomFont';
            src: url('font/CustomFont.ttf');
        }
        #font {
            font-family: 'CustomFont';
        }
    </style>
</head>
<body>
    <p>No Font</p>
    <br />
    <p id="font">Font</p>
</body>

使用Webview#loadDataWithBaseURL(String,String,String)将此HTML加载到webview中,使用file:// android_res /作为基本URL(第一个参数)

例:

webview.loadDataWithBaseURL("file:///android_res/",html,null)

编辑:

如果您在发布版本中使用proguard,则需要添加额外的规则以防止在ProGuard过程中重命名R类,否则WebView将无法找到字体资源.详细信息可在this post找到

大佬总结

以上是大佬教程为你收集整理的在Android中使用来自res / font的自定义字体与WebView全部内容,希望文章能够帮你解决在Android中使用来自res / font的自定义字体与WebView所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。