How to set title in app bar with Navigation Architecture Component

前端 未结 12 2017
面向向阳花
面向向阳花 2020-12-24 11:40

I was trying out Navigation architecture component and is now having difficulties in setting the title. How do I set the title programmatically and also how it works?

<
12条回答
  •  情话喂你
    2020-12-24 12:36

    You can use the navigation graph xml file and set the label of the fragment to an argument. Then, in your parent fragment, you can pass an argument using SafeArgs and provide a default value to avoid the title being null or empty.

    
    
        
    
    

    In originating Fragment:

     String text = "text to pass";
     CharactersListFragmentDirections.CharacterDetailAction action = CharactersListFragmentDirections.characterDetailAction();
     action.setCharacterName(text);
     Navigation.findNavController(v).navigate(action);
    

    CharactersListFragmentDirections and CharacterDetailAction - These classes are autogenerated from IDs in your nav_graph.xml file. In 'your action ID + Action' type classes you can find auto-generated setter methods, which you can use to pass arguments

    
            
        
    

    In your receiving destination (xml layout file is at the top of this answer) you call auto generated class {your receiving fragment ID}+Args

    CharacterDetailFragmentArgs.fromBundle(requireArguments()).getCharacterName();
    

    Please refer to official guide https://developer.android.com/guide/navigation/navigation-pass-data#Safe-args

提交回复
热议问题