Reputation: 1528
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)?
Upvotes: 0
Views: 1339
Reputation: 2817
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);
}
}
Upvotes: 1
Reputation: 812
if you are using viewPager then you can do this using only single toolbar in your MainActivity
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
if(position==YourFragmentPosition)
{
toolbar.setVisibility(View.VISIBLE);
}
else{
toolbar.setVisibility(View.GONE);
}
}
}
@Override
public void onPageScrollStateChanged(int state) {
});
Upvotes: 0
Reputation: 4127
Since you want different representations, each of your fragments should have (when you want) their own toolbar
.
Hence your Activity
's layout will have a simple fragment_container.
Upvotes: 0