CollapsingToolbarLayout 字体不以编程方式更改

CollapsingToolbarLayout typeface not changing programmatically

设置自定义字体出现意外错误后出现问题。为什么在我将字体添加到正确的位置后还会出现此错误?

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

如果你把字体设置成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)
    }
}

如果您将字体设置为 res/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 = ResourcesCompat.getFont(this, R.font.my_font)
        collapsingToolbarLayout.title = getString(R.string.main_activity)
        collapsingToolbarLayout.setCollapsedTitleTypeface(mTypeface)
        collapsingToolbarLayout.setExpandedTitleTypeface(mTypeface)
    }
}