Reputation: 8408
When using a custom typeface in a settings fragment which context needs be used in this scenario? I know that this
needs to be change but I couldn't find any relevant tutorials on this.
Type mismatch. Required: Context. Found: 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)
}
Upvotes: 0
Views: 288
Reputation: 93639
Unlike Activities, Fragments are not subclasses of Context. You'll see many Android tutorials where this
is passed as the Context argument to some function, and that's because they are calling that code from inside an Activity instead of from a Fragment.
Fragments have a context
property you can use, but it is null
before the Fragment gets attached to an Activity (like when the class is initialized) and after it is detached.
You can use the lazy
property delegate, so the context will not be null when the getFont
function is called. But if you do this, don't access the property from a callback that could be called after the fragment is detached.
private val mTypeface by lazy { ResourcesCompat.getFont(requireContext(), R.font.open_dyslexic_regular) }
Upvotes: 1
Reputation: 5241
In fragment you can call getContext or getActivity instead of pass this when get custom font. But your code will be crash because when fragment not attach to host context is null try to change
private val mTypeface : Typeface get() = ResourcesCompat.getFont(requireContext(), R.font.open_dyslexic_regular)
Upvotes: 0