将字体字体分配给文本视图的最佳方法

Best way to assign font typeface to textview

我想知道将字体字体分配给 TextView 视图的最佳方法是什么?创建一个扩展 TextView 或使用 setTypeFace 属性的自定义 TextView class 更好吗?

创建文件夹 assets(src/main/assets/ 在 Android Studio 中)并创建一个子文件夹 fonts ,将您的字体复制到其中

 Typeface tf = Typeface.createFromAsset(getAssets(),
    "fonts/youi.ttf");
 TextView tv = (TextView) findViewById(R.id.edit_t);
 tv.setTypeface(tf);

这是这个的 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了解更多