如何使用 Kotlin 更改 android 中的字体?

How can I change the fonts in android using Kotlin?

我正在尝试更改字体,但不起作用。返回 "null" 是因为我在 XML 和代码中设置了值。

Kotlin 代码

 val typeFace = Typeface.createFromAsset(tvThanks.context.assets, "dinpro_medium.ttf")
        tvThanks.setTypeface(typeFace)
<TextView
    android:id="@+id/tvThanks"
    android:layout_width="150dp"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:text="@string/text_here"/>

错误

java.lang.IllegalStateException: tvThanks must not be null
    at br.com.adrianofpinheiro.testesantander.fragment.ContatoEnviadoFragment.onCreate(ContatoEnviadoFragment.kt:21)

您的片段应该有 context 属性 而不是来自 tvThanks

我认为你可以尝试在片段

onCreateView 中执行此操作
 val typeFace = Typeface.createFromAsset(context.assets, "dinpro_medium.ttf")
        tvThanks!!.setTypeface(typeFace)
class Photos : Fragment() {
private lateinit var rootView: View
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    rootView = inflater.inflate(R.layout.skeleton_photos_tab, container, false)
    return rootView
}

}

现在你可以做到了。

rootView.tvThanks.setTypeface(typeFace)