Hide android.support.v7.widget.Toolbar programmatically

In my activity I do:

setSupportActionBar(toolbar); 

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

Is there any way after that to hide and show the toolbar widget programmatically? I have already tried

 toolbar.setVisibility(View.INVISIBLE); 

but this makes it invisible, and it still occupies a space, so after it an activity starts, and I see an empty space in the header.

+6
source share
3 answers

INVISIBLE hides only the view.

GONE , however, will hide the view and prevent it from engaging in any space.

 toolbar.setVisibility(View.GONE); 
+14
source

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

 setExpanded(boolean expanded, boolean animate) 

This method is available from the v23 support library.

From the documentation for reference.

As with scrolling through an AppBarLayout, this method relies on this layout, which is a direct child of the CoordinatorLayout.

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

animate: whether to animate a new state

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

to expand the toolbar using animation.

 appBarLayout.setExpanded(true, true); 

to collapse the toolbar using animation.

 appBarLayout.setExpanded(false, true); 
+4
source

Here is my code, try this. This worked great 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 helps you.

0
source

Source: https://habr.com/ru/post/980813/


All Articles