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)
}
To change background color of Action Bar in Kotlin Android, set the colorPrimary in themes. xml, with a required color. We can also dynamically change the background color of Action Bar programmatically by setting background drawable for support action bar with the required color drawable.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml. In the above code, we have taken text view to show status bar tittle.
In Android applications, ActionBar is the element present at the top of the activity screen. It is a salient feature of a mobile application that has a consistent presence over all its activities.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With