【发布时间】:2015-04-07 17:25:12
【问题描述】:
我想知道将字体分配给 TextView 视图的最佳方式是什么?是创建一个扩展 TextView 的自定义 TextView 类还是使用 setTypeFace 属性更好?
【问题讨论】:
标签: android textview android-custom-view android-fonts android-typeface
我想知道将字体分配给 TextView 视图的最佳方式是什么?是创建一个扩展 TextView 的自定义 TextView 类还是使用 setTypeFace 属性更好?
【问题讨论】:
标签: android textview android-custom-view android-fonts android-typeface
创建文件夹 assets(src/main/assets/ in AndroidStudio) 并创建一个子文件夹 fonts ,将你的字体复制到其中
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/youi.ttf");
TextView tv = (TextView) findViewById(R.id.edit_t);
tv.setTypeface(tf);
【讨论】:
createFromAsset 存在一个已知问题。它不是维护它的引用,而是在每次调用它时尝试重新创建字体。如果您打算经常使用它,您可能应该缓存它。
这是这个的 kotlin 版本
val openSansLight: Typeface by lazy { Typeface.createFromAsset(context, "font/os_light.ttf"); }
textView.typeface = openSansLight
【讨论】:
字体现在是应用资源的一部分!您现在可以使用字体系列属性来更改 xml 中的字体。创建字体资源目录,可以放字体文件。
android:fontFamily="@font/lobster"
使用代码
val typeface = resources.getFont(R.font.myfont)
textView.typeface = typeface
更多信息请参考official documentation
【讨论】: