Search code examples
androidandroid-jetpackandroid-jetpack-navigation

How to change label dynamically in Fragment?


I want to change the "android:label" in Fragment

I tried to run the following code to change label, but It failed.

val graph = findNavController().graph
graph.label = "测试"
findNavController().graph = graph

Solution

  • As per the Navigation UI documentation, the NavigationUI methods, such as the setupActionBarWithNavController() method rely on an OnDestinationChangedListener, which gets called every time you navigate() to a new destination. That's why the label is not instantly changed - it is only updated when you navigate to a new destination.

    The documentation does explain that for the top app bar:

    the label you attach to destinations can be automatically populated from the arguments provided to the destination by using the format of {argName} in your label.

    This allows you to update the string you use for your label (say R.string.destination_label) to be in the form of

    <string name="destination_label">You are on {destination}</string>
    

    By using that same argument on your destination, your title will automatically be populated with the correct information.

    Of course, if you don't have an argument that you can determine ahead of time, then you'd want to avoid setting an android:label on your destination at all and instead manually update your action bar's title, etc. from that destination.