In my android application I have one activity and many fragments. However, I only want to show the toolbar for some fragments, for the others I want the fragment to be fullscreen. What's the best and recommended way to do this (show and hide the activity toolbar according to the visible fragment)?
I preferred using interface for this.
public interface ActionbarHost {
void showToolbar(boolean showToolbar);
}
make your activity implement ActionbarHost
and override showToolbar as.
@Override
public void showToolbar(boolean showToolbar) {
if (getSupportActionBar() != null) {
if (showToolbar) {
getSupportActionBar().show();
} else {
getSupportActionBar().hide();
}
}
}
Now from your fragment initialize from onAttach()
private ActionbarHost actionbarHost;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof ActionbarHost) {
actionbarHost = (ActionbarHost) context;
}
}
now just if you want to hide action bar call actionbarHost.showToolbar(false);
from fragment.
if (actionbarHost != null) {
actionbarHost.showToolbar(false);
}
Also I'd suggest to show it again in onDetach()
@Override
public void onDetach() {
super.onDetach();
if (actionbarHost != null) {
actionbarHost.showToolbar(true);
}
}