Search code examples
androidandroid-fragmentsnavigation-drawerandroid-toolbar

NavigationDrawer - Different toolbar for each fragment


I have an app with a single Activity(MainActivity) and a Navigation Drawer. The navigation drawer, of course, opens the fragments in the activity. The problem I am facing is that I have already linked the MainActivity toolbar to the ActionToggle (hamburger) when I created an object of the ActionToggle. So the MainActivity toolbar shows in all fragments, but I want different toolbar XML for each fragments. If I want to hide the MainActivity toolbar in the fragments, the ActionToggle (hamburger) will also get hidden.

Please, how can I have different toolbar for each fragment, with the MainActivity ActionToggle in all the toolbars?


Solution

  • I would have expected the question to be clearer, but as I understand it, I can help you in the following way.

    -If you want to change your toolbar from within different fragments, below code block can help you.

    Toolbar toolbar = view.findViewById(R.id.toolbar);
    ((MainActivity) getActivity()).getSupportActionBar().hide();
    ((MainActivity) getActivity()).setSupportActionBar(toolbar);
    

    -If you just want to change the toolbar properties such as the title, you can use the code block below.

    Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
    toolbar.setTitle("title");