Dynamic Actionbar Title From A Fragment Using Androidx Navigation
Solution 1:
As of 1.0.0-alpha08
, you can have the NavigationUI bits dynamically set the title... if the dynamic bits are arguments on the navigation action.
So, for example, in your navigation graph, you could have something like this:
<fragmentandroid:id="@+id/displayFragment"android:name="com.commonsware.jetpack.sampler.nav.DisplayFragment"android:label="Title: {title}" ><argumentandroid:name="modelId"app:argType="string" /><argumentandroid:name="title"app:argType="string" /></fragment>
Here, the android:label
attribute for our <fragment>
has an argument name wrapped in braces ({title}
in "Title: {title}"
. The app bar's title will then be set to the value of the label, with {title}
replaced by the value of the title
argument.
If you need something more elaborate than that — for example, you want to look up the model by ID and read a property from it — you will need to use more manual approaches, such as those outlined in other answers to this question.
Solution 2:
The title can be changed in the fragment by casting the activity as AppCompatActivity
.
Kotlin
(requireActivity() as AppCompatActivity).supportActionBar?.title = "Hello"
Java
((AppCompatActivity) requireActivity()).getSupportActionBar().setTitle("Hello");
Solution 3:
Taking consideration that your host activity is MainActivity
, just add the following code to your MainActivity
's onCreate
fun
val navController = Navigation.findNavController(this, R.id.nav_host_fragment)
// setting title according to fragment
navController.addOnDestinationChangedListener {
controller, destination, arguments ->
toolbar.title = navController.currentDestination?.label
}
Solution 4:
If you use toolbar on setSupportActionBar in Activity and you would like to change its title in fragment, then below code may gonna help you ;)
(requireActivity() as MainActivity).toolbar.title = "Title here"
Solution 5:
As of now, The Jetpack Navigation Architecture components do not provide any "built in" way to do this, and you'll have to implement your own "custom" method for doing it.
There is an existing feature request to get functionality for dynamic labels on destinations added to the new Jetpack Navigation Architecture Components. If you are here because you want/need this functionality, please star the existing feature request, here: https://issuetracker.google.com/issues/80267266
Post a Comment for "Dynamic Actionbar Title From A Fragment Using Androidx Navigation"