Android dynamically set actionbar title with navigation and safe args
With Jetpack navigation and safe args, the actionbar title can be set dynamically with safe args.
Here is a xml file for the navigation graph with 2 fragments, nav_main_fragment and nav_detail_fragment. The actionbar title is set by the android:label
attribute on the fragment. In the detail fragment, there is a safe arg defined with name myactionbartitle. This actionbar title also shows up as the value for fragment’s label attribute as android:label="{myactionbartitle}"
in inside a pair of curly brackets. This will automatically set the actionbar title with the value that is passed to the fragment via safe arg with the argument name myactionbartitle.
Navigating from the main fragment to the detail fragment, and pass in a string “My Detail Fragment” for myactionbartitle on the action. When the detail fragment is launched, it will automatically sets the actionbar title with “My Detail Fragment”, because in the navigation graph above it sets the label to the value of safe arg myactionbartitle.
val action = MainFragmentDirections.actionNavMainFragmentToNavDetailFragment( myactionbartitle = "My Detail Fragment" ) findNavController().navigate(action)
Search within Codexpedia
Search the entire web