Home » Android » Hide android.support.v7.widget.Toolbar programmatically

Hide android.support.v7.widget.Toolbar programmatically

Posted by: admin May 14, 2020 Leave a comment

Questions:

In my activity I do:

setSupportActionBar(toolbar);

where toolbar is an instance of android.support.v7.widget.Toolbar

Is there any way after this to hide and show back Toolbar widget programmatically? I already tried

toolbar.setVisibility(View.INVISIBLE);

but this only makes it invisible and it still takes space, so that content of the activity starts after it, and I see white space instead in the header.

How to&Answers:

INVISIBLE only hides the view.

GONE however, will hide the view and prevent it from taking up any space.

toolbar.setVisibility(View.GONE);

Answer:

If your toolbar is inside the AppBarLayout then you can use setExpanded method of AppBarLayout to expand and collapse the toolbar with or without animation.

setExpanded(boolean expanded, boolean animate)

this method is available from v23 of Support Library.

From the documentation for reference.

As with AppBarLayout scrolling, this method relies on this layout being a direct child of a CoordinatorLayout.

expanded : true if the layout should be fully expanded, false if it should be fully collapsed

animate : Whether to animate to the new state

AppBarLayout appBarLayout = (AppBarLayout)findViewById(R.id.appBar);

to expand the toolbar with animation.

appBarLayout.setExpanded(true, true);

to collapse the toolbar with animation.

appBarLayout.setExpanded(false, true);

Answer:

Here is my code try this. It worked perfectly for me.

    private static final float APPBAR_ELEVATION = 14f;

    private void hideAppBar(final AppBarLayout appBar) {
                appBar.animate().translationY(-appBar.getHeight()).setInterpolator(new LinearInterpolator()).setDuration(500);

    }
    public void showAppBar(final AppBarLayout appBar){
                appBar.animate().translationY(0).setInterpolator(new LinearInterpolator()).setDuration(500).setListener(new AnimatorListenerAdapter() {
                            @Override
                            public void onAnimationEnd(Animator animation) {
                                appBar.setElevation(APPBAR_ELEVATION);
                            }
                });
    }

Hope this might help you