I'm trying to set the toolbar title dynamically, I don't know if it's possible or not.
Assume I have list of items every item I clicked it's open new fragment, thus I trying to change toolbar title for each item dynamically.
I tried :
it.findNavController().navigate(direction)
it.findNavController().currentDestination!!.label = someTitle
But it doesn't work.
There are some related topics i.e:
How to set title in app bar with Navigation Architecture Component
But it doesn't solve my problem efficiently, It's a work-around.
To use a DrawerLayout, position your primary content view as the first child with width and height of match_parent and no layout_gravity> . Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.
Configuration options for NavigationUI methods that interact with implementations of the app bar pattern such as androidx. appcompat. widget. Toolbar , com. google.
Navigation supports arguments in labels as of Navigation 1.0.0-alpha08 or higher:
Destination labels, when used with NavigationUI methods, will now automatically replace
{argName}
instances in yourandroid:label
with the correct argument b/80267266
Therefore you can set your label to android:label="{dynamicTitle}"
, then pass in an argument to your navigate
call. As you're using Safe Args, you'd want to add an argument to your destination:
<fragment
android:id="@+id/myFragment"
android:name=".MyFragment"
android:label="{dynamicTitle}">
<argument
android:name="dynamicTitle"
app:argType="string"/>
</fragment>
Then pass in your dynamic title when constructing your directions:
val directions = YourDirections.actionToMyFragment(someTitle)
it.findNavController().navigate(directions)
Of course, you can listen for navigation events yourself and use your own OnDestinationChangedListener
to do whatever you want, including setting the label to whatever you want. There's no requirement to use NavigationUI and any listener to add after calling the NavigationUI methods will override whatever it sets.
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