bagya gunawardana
bagya gunawardana

Reputation: 288

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

Upvotes: 15

Views: 19293

Answers (4)

Polymath
Polymath

Reputation: 862

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"

}

Upvotes: 1

niek tuytel
niek tuytel

Reputation: 1179

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"

Upvotes: 2

Kasun Thilina
Kasun Thilina

Reputation: 1681

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

Upvotes: 1

Fred
Fred

Reputation: 17085

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.

Upvotes: 33

Related Questions