class App : Application() {
override fun onCreate() {
super.onCreate()
initTypeface()
}
private fun initTypeface() {
val typefaceBysong = Typeface.createFromAsset(assets, "fonts/bysong.ttf")
val monospace = Typeface::class.java.getDeclaredField("MONOSPACE")
monospace.isAccessible = true
monospace.set(null, typefaceBysong)
}
}
3.定义app的style(主要是4.设置在manifests文件中设置application,替换theme="@style/AppTheme.NoActionBar"
这样全部都替换成第三方字体,对于字体因为太大而导致的问题,可以将字体的扩展名改成zip或者jpg就会解决。
二.单个TextView替换 1.对每个TextView调用 setTypeface(@Nullable Typeface tf)方法class FontActivity : AppCompatActivity() {
private lateinit var mBinding: ActivityFontBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mBinding = ActivityFontBinding.inflate(LayoutInflater.from(this))
setContentView(mBinding.root)
//得到AssetManager
val typefaceBysong = Typeface.createFromAsset(assets, "fonts/bysong.ttf")
//设置字体
mBinding.textViewThird.typeface = typefaceBysong
}
}
但是这样未免有些麻烦,需要对每个TextView调用 setTypeface(@Nullable Typeface tf)方法,于是还可以这样
2在res资源文件夹下新建font文件夹,将三方字体资源文件导入
对TextView添加android:fontFamily="@font/fzkatong"标签即可
三.官方指南文档
字体资源 | Android 开发者 | Android Developers



