Search code examples
androidandroid-fragmentskotlinandroid-actionbar

How to Change ActionBar title in fragment class in kotlin?


I'm new to android development in kotlin. I tried the following code to change the actionbar title from my fragment.It's not working.Please help

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


    activity.actionBar?.title = "Example 1"
    countBtn.setOnClickListener(this)
    toastBtn.setOnClickListener(this)
    randomBtn.setOnClickListener(this)

}

MainActivity.kt code is as below

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


    setSupportActionBar(toolbar)
    val actionBar = supportActionBar
    actionBar?.title = getString(R.string.toolbar_title)
}

Solution

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