Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
231 views
Welcome To Ask or Share your Answers For Others

1 Answer

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...