Home > Software design >  Changing action bar title dynamically not working
Changing action bar title dynamically not working

Time:11-19

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

CodePudding user response:

  • 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 = ...
  • Related