在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 如何解决dialog弹出时无法捕捉Activity的back事件 在...
Android实现自定义带文字和图片的Button 在Android开发中经常...
Android 关于长按back键退出应用程序的实现最近在做一个Andr...
android自带的时间选择器只能精确到分,但是对于某些应用要求...