Different toolbar for fragments and Navigation Drawer

后端 未结 5 1786
花落未央
花落未央 2020-12-16 01:35

Please, explain to me... I have Navigation Drawer in my Activity and it syncs with Toolbar (like ActionBar). Activity has few fragment

5条回答
  •  Happy的楠姐
    2020-12-16 01:56

    If you want to use appbar(toolbar) that you specified in navigation drawer in different fragments with, for example different options menu items, you could make a public method in Main Activity where you specified your navigation drawer logic.

    public void setToolbar(Toolbar toolbar, String title){
        AppCompatActivity actionBar = this;
        actionBar.setSupportActionBar(toolbar);
    
        DrawerLayout drawer = (DrawerLayout)actionBar.findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toogle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.drawer_open, R.string.drawer_close);
        drawer.addDrawerListener(toogle);
        toogle.setDrawerIndicatorEnabled(true);
        toogle.syncState();
        if(toolbar != null)
            toolbar.setTitle(title);
    }
    


    Now you can use this method in your fragments to access the main toolbar and override it with your custom title, options menu... You can do this by creating a new toolbar variable in your fragment and then inflate it in onCreateView() method like this

    toolbarFragment = (Toolbar)getActivity().findViewById(R.id.toolbar);
    

    R.id.toolbar is the id of a toolbar that you specified in your layout file and it is the same id that you used in your main activity for the main toolbar.


    Now you can call the method setToolbar(Toolbar toolbar, String title) in fragment like this

    ((MainActivity)getActivity()).setToolbar(toolbarFragment, "Some title");
    


    If you want to use options menu for this fragment you have to call

    setHasOptionsMenu(true);
    

    in fragments onCreate() or onCreateView() methods. After that you can override method onCreateOptionsMenu() like this

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.custom_menu1, menu);
    }
    

    You can repeat this procedure for other fragments in your navigation drawer as well. Although it worked for me, I don't know if this violates activities or fragments lifecycle or causes memory leeks.

提交回复
热议问题