当在设置片段中使用自定义字体时,在这种情况下需要使用哪种上下文?我知道 this
需要改,但我找不到相关的教程。
类型不匹配。需要。Context. 发现。SettingsFragment
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preferences)
}
private val mTypeface = ResourcesCompat.getFont(this, R.font.open_dyslexic_regular)
}
与Activity不同,Fragments不是Context的子类。你会看到很多安卓教程,其中 this
是作为Context参数传递给某个函数的,那是因为他们是从Activity内部而不是从Fragment调用该代码的。
Fragment有一个 context
你可以使用的属性,但它是 null
在Fragment被附加到Activity之前(比如当类被初始化时)和在它被分离之后。
你可以使用 lazy
属性委托,因此当 getFont
函数被调用。但如果你这样做,不要从回调中访问该属性,因为回调可能会在片段脱离后被调用。
private val mTypeface by lazy { ResourcesCompat.getFont(requireContext(), R.font.open_dyslexic_regular) }
在fragment中,你可以调用getContext或getActivity,而不是在获取自定义字体时传递这个属性。但是你的代码会崩溃,因为当fragment没有附加到主机上下文是null时,试图改变
private val mTypeface : Typeface get() = ResourcesCompat.getFont(requireContext(), R.font.open_dyslexic_regular)