Please, explain to me... I have Navigation Drawer in my Activity and it syncs with Toolbar (like ActionBar). Activity has few fragment
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);
}
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.
setToolbar(Toolbar toolbar, String title) in fragment like this
((MainActivity)getActivity()).setToolbar(toolbarFragment, "Some title");
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.