Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set toolbar title dynamically using navigation-component

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.

like image 362
Ibrahim Ali Avatar asked Apr 16 '19 04:04

Ibrahim Ali


People also ask

How to use DrawerLayout in android?

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.

What is Appbarconfiguration in Android Studio?

Configuration options for NavigationUI methods that interact with implementations of the app bar pattern such as androidx. appcompat. widget. Toolbar , com. google.


1 Answers

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 your android: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.

like image 186
ianhanniballake Avatar answered Sep 17 '22 17:09

ianhanniballake