androidkotlinandroid-collapsingtoolbarlayoutandroid-fontsandroid-typeface

CollapsingToolbarLayout typeface not changing programmatically


Setting a custom typeface is becoming problematic after getting an unexpected error. Why is this error even appearing when I've added a font to the correct location?

font/my_font.otf

Attempt to invoke virtual method 'boolean android.content.Context.isRestricted()' on a null object reference

class MainActivity : AppCompatActivity() {
    private val mTypeface = Typeface.createFromAsset(assets, "my_font.otf")

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        collapsingToolbarLayout.title = getString(R.string.main_activity)
        collapsingToolbarLayout.setCollapsedTitleTypeface(mTypeface)
        collapsingToolbarLayout.setExpandedTitleTypeface(mTypeface)
    }
}

Solution

  • If you put your font in assets/font/my_font.otf:

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            //This should solve your crashing problem
            val typeface = Typeface.createFromAsset(assets, "font/my_font.otf")
            collapsingToolbarLayout.title = getString(R.string.main_activity)
            collapsingToolbarLayout.setCollapsedTitleTypeface(mTypeface)
            collapsingToolbarLayout.setExpandedTitleTypeface(mTypeface)
        }
    }
    

    If you put your font in res/font/my_font.otf (RECOMMENDED):

    class MainActivity : AppCompatActivity() {
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            //This should solve your crashing problem
            val typeface = ResourcesCompat.getFont(this, R.font.my_font)
            collapsingToolbarLayout.title = getString(R.string.main_activity)
            collapsingToolbarLayout.setCollapsedTitleTypeface(mTypeface)
            collapsingToolbarLayout.setExpandedTitleTypeface(mTypeface)
        }
    }