【问题标题】:How can I change the fonts in android using Kotlin?如何使用 Kotlin 更改 android 中的字体?
【发布时间】:2019-05-18 20:12:55
【问题描述】:

我正在尝试更改字体,但无法正常工作。正在返回“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)

【问题讨论】:

  • 您在 Kotlin 代码中的何处定义 tvThanks
  • 片段内的视图在onCreate 期间不存在。将您的代码移至onViewCreated

标签: android kotlin fonts textview


【解决方案1】:

您的片段应该具有context 属性,而无需从tvThanks 获取。

我认为您可以尝试在片段的onCreateView 中执行此操作

 val typeFace = Typeface.createFromAsset(context.assets, "dinpro_medium.ttf")
        tvThanks!!.setTypeface(typeFace)

【讨论】:

    【解决方案2】:
    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-08
      • 1970-01-01
      • 2011-11-22
      • 1970-01-01
      • 2014-04-10
      • 2022-01-21
      相关资源
      最近更新 更多