0

I have an activity with a toolbar from a default layout in Android Studio and I can easily change the title in the toolbar through the following method:

    Bundle bundle = new Bundle();
    bundle.putString("toolbarTitle", "A new title");

    NavHostFragment
        .findNavController(this)
        .navigate(R.id.action_navigation_conversation_to_placeholder, bundle);

Where safe args is already implemented for toolbarTitle in the navigation menu layout.

However now I am trying to change the title from the fragment that is opened via the method above, for example;

  • MyActivity ->opens-> MyFragment

  • MyFragment changes title

I do know how to update it without using Navigation UI Components, but I want to use them if it is possible.

Other similar questions are only related to the example I already provided above for when a new fragment is being opened or by suggesting the use of the typical method that does not make use of the Navigation UI Components, none cover this specific scenario.

Shadow
  • 4,168
  • 5
  • 41
  • 72
  • So you're trying to change the toolbar title when you navigate to the new destination? Is this a fixed title that is always the same for that destination or something more dynamic? – ianhanniballake Aug 17 '20 at 01:15
  • It's a dynamic title that is to be set from the fragment that is opened, otherwise I would've just set the label directly in the navigation menu layout – Shadow Aug 17 '20 at 01:16
  • An example that can clarify the above is a title made out of a list of users currently in a chat (fragment) and those users can leave or join, thus changing the title when that happens. – Shadow Aug 17 '20 at 01:26

2 Answers2

4

You can change the the title by accesing the supportActionBar from the activity:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    (requireActivity() as AppCompatActivity).supportActionBar?.title = "Your Title"
}
0

It seems like this is not possible with the only way to achieve this by doing it directly without using the Navigation Architecture Components.

Shadow
  • 4,168
  • 5
  • 41
  • 72