Search code examples
androidkotlinandroid-fontsandroid-typeface

Type mismatch when trying to declare custom typeface


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)
}

Solution

  • 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) }