By following this and this MO posts I tried to set title of app bar of my android project as follow:
MainActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setSupportActionBar(findViewById(R.id.toolbar));
navController = Navigation.findNavController(this, R.id.navHostFragment);
navController.addOnDestinationChangedListener((controller, destination, args) -> {
// Check if it's a root destination
NavGraph destinationGraph = destination.getParent();
boolean isRootDestination = destinationGraph != null &&
destinationGraph.getStartDestinationId() == destination.getId();
// Update back button accordingly
Objects.requireNonNull(getSupportActionBar())
.setDisplayHomeAsUpEnabled(!isRootDestination);
// Update activity title
setTitle(destination.getLabel());
});
}
fragments_Graph.xml
<fragment
android:id="@+id/fragmentA"
...
android:label="Fragment A"
... >
<action
android:id="@+id/action_fragmentA_to_fragmentB"
app:destination="@id/fragmentB"
app:launchSingleTop="true" />
</fragment>
<fragment
android:id="@+id/fragmentB"
...>
<action
android:id="@+id/action_fragmentB_to_fragmentA"
app:destination="@id/fragmentA"
app:launchSingleTop="true" />
</fragment>
and inside of onCreate
of Fragment B
i used:
requireActivity().setTitle("some title");
everything is working fine in forward direction but when I press back arrow in Fragment B, Title of Fragment A become "some title"!! What is the problem??
When I add another fragment with predefined title (in graph.xml, i.e. android:label="Fragment New") before Fragment A, navigating up and back between fragments A and New one work fine and AppBar title show what specified.
Update:
I tried to use the following but the issue remains the same (i.e. Fragment A -> New Label! (fragment B), and in back direction: New Label! -> New Label! (fragment A) ):
if(destination.getLabel()==null){
destination.setLabel("New Label!");
setTitle(destination.getLabel());
} else {
setTitle(destination.getLabel());
}