How to Change ActionBar title in fragment class in kotlin?

It seems like you're setting the support action bar, so you'd have to use the support action bar in the onCreateView method too. The actionBar is null, that's why the code to set the title won't run.

Try this out:

override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
  super.onViewCreated(view, savedInstanceState)

  (activity as AppCompatActivity).supportActionBar?.title = "Example 1"
  //...
}

The other problem I think you might run into is that you're adding the support action bar in the activity's onCreate method, but you're trying to access it in the fragment's onViewCreated which comes before according to this (I haven't really tried this out, it's just from looking at the diagram). If this is the case, then you'd have to change it. Maybe try the onStart from the fragment.


Try:

override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
    super.onCreateOptionsMenu(menu, inflater)
    inflater.inflate(R.menu.options_menu, menu)

    (activity as AppCompatActivity).supportActionBar?.title = "My Fragment Title"

}

It worked for me on the onViewCreated Method

override fun onViewCreated() {    
    (activity as AppCompatActivity).setSupportActionBar(toolbar_name)
    (activity as AppCompatActivity).supportActionBar?.title = getString(R.string.title)
    }

this page explain very well how to set a Toolbar :

https://developer.android.com/training/appbar/setting-up#kotlin

than changing things on the tool bar:

setSupportActionBar(findViewById(R.id.my_toolbar))
supportActionBar!!.title = "new title of toolbar"