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

 收藏

我正在尝试更改字体,但无法正常工作。返回“ null”是因为我在XML和代码中都设置了值。

科特林密码

 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)
回复
  • 你无可取代 回复

    Your fragment should have the context property without getting from the tvThanks.

    I think you can try doing this inside the onCreateView of your fragment

     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)