How to change label dynamically in Fragment? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of How to change label dynamically in Fragment? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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


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.

We are here to answer your question about How to change label dynamically in Fragment? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji