繁体   English   中英

未解决的参考:Android Studio 中的字体

[英]Unresolved reference: font in Android Studio

我正在尝试将字体设置为 android studio 中的文本视图,但由于某些原因,我无法访问字体目录。

我得到未解决的参考:字体

我做了什么

-通过右键单击 res > new > Android Resource Directory > Directory name : font > Resource type : font 创建一个新目录

-将我的字体放在该目录中,因此该目录显示为 - res/font/myfont.ttf

-在我的片段中,我尝试像这样访问字体

var typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.myfont.ttf)

错误显示未解决的参考:字体

我试图重建项目但仍然无法正常工作。

用:

字体:字体? = ResourcesCompat.getFont(requireContext(), R.font.myfont)

不要添加.ttf扩展名。

public static Typeface getFont(上下文上下文,int id)

返回与特定资源 ID 关联的字体 Typeface。

试试

typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.myfont)

仅供参考 - 阅读有关Fonts in XML官方指南

Android 8.0(API 级别 26)引入了一项新功能,XML 中的字体,可让您将字体用作资源。 您可以在 res/font/ 文件夹中添加字体文件,将字体捆绑为资源。 这些字体在您的 R 文件中编译,并在 Android Studio 中自动可用。 您可以在新资源类型 font 的帮助下访问字体资源。 例如,要访问字体资源,请使用@font/myfontR.font.myfont

笔记

可以直接调用自定义字体ttf/otf。 使用createFromAsset

 val font = Typeface.createFromAsset(requireContext().assets,"font/myfont.ttf")

问题在于:

  • 导入的“R”类是框架资源“ android.R

  • 我不得不删除它并导入我的项目“R”“com.myproject.project.R”

像这样打电话

  • val typeFace: Typeface? = ResourcesCompat.getFont(requireContext(), R.font.poppings)

又没有错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM