Search code examples
androidkotlinandroid-actionbar

Changing action bar title dynamically not working


I want to change the text of the action bar in a fragment dynamically when that fragment is created,but activity?.actionBar?.title = movie.title is not working.

I tried this too

activity?.actionBar?.setDisplayShowTitleEnabled(true)
activity?.actionBar?.title = movie.title

Solution

    • actionBar is deprecated and replaced with supportActionBar.
    • Using activity within a fragment returns FragmentActivity which doesn't directly reference supportActionBar object; instead you need to cast that to AppCompatActivity) or to your custom name of the activity that hosts this fragment.

    To fix this:

    (requireActivity() as AppCompatActivity).supportActionBar?.setDisplayShowTitleEnabled(true)
    (requireActivity() as AppCompatActivity).supportActionBar?.title = ...