在Android中使用来自res / font的自定义字体与WebView

前端之家收集整理的这篇文章主要介绍了在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使用自定义字体系列?

//编辑:

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

  1. @BindingAdapter("loadData")
  2. public static void loadData(WebView webView,String htmlData) {
  3. webView.loadDataWithBaseURL(null,htmlData,"text/html","utf-8",null);
  4. }
  5.  
  6. @BindingAdapter({"loadData","fontFamily"})
  7. public static void loadData(WebView webView,String htmlData,@FontRes int fontFamilyId) {
  8. TypedValue value = new TypedValue();
  9. ApplicationActivity.getSharedApplication().getResources().getValue(fontFamilyId,value,true);
  10. String fontPath = value.string.toString();
  11. File fontFile = new File(fontPath);
  12.  
  13. String prefix = "<html>\n"
  14. +"\t<head>\n"
  15. +"\t\t<style type=\"text/css\">\n"
  16. +"\t\t\t@font-face {\n"
  17. +"\t\t\t\tfont-family: 'CustomFont';\n"
  18. +"\t\t\t\tsrc: url(\"file:///android_res/font/"+fontFile.getName()+"\")\n"
  19. +"\t\t\t}\n"
  20. +"\t\t\tbody {\n"
  21. +"\t\t\t\tfont-family: 'CustomFont';\n"
  22. +"\t\t\t}\n"
  23. +"\t\t</style>\n"
  24. +"\t</head>\n"
  25. +"\t<body>\n";
  26. String postfix = "\t</body>\n</html>";
  27.  
  28. loadData(webView,prefix + htmlData + postfix);
  29. }

解决方法

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

示例HTML

  1. <html>
  2. <head>
  3. <style>
  4. @font-face {
  5. font-family: 'CustomFont';
  6. src: url('font/CustomFont.ttf');
  7. }
  8. #font {
  9. font-family: 'CustomFont';
  10. }
  11. </style>
  12. </head>
  13. <body>
  14. <p>No Font</p>
  15. <br />
  16. <p id="font">Font</p>
  17. </body>

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

例:

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

编辑:

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

猜你在找的Android相关文章