Hiding AppBarLayout and giving its space to the remaining view

natario picture natario · Jun 16, 2015 · Viewed 11.4k times · Source

I have a pretty standard layout using the new design libraries:

<AppBarLayout>
    <CollapsingToolbarLayout>
        <ImageView/>
        <Toolbar/>
    </CollapsingToolbarLayout>
</AppBarLayout>

<android.support.v4.widget.NestedScrollView/> <!-- content here -->

What I'm trying to do is to completely hide the whole AppBarLayout programmatically, to temporarily get rid of the Toolbar and its collapsing feature.

So I'm calling this:

private void disableCollapsing() {
    AppBarLayout.LayoutParams p = (AppBarLayout.LayoutParams) collapsingToolbarLayout.getLayoutParams();
    p.setScrollFlags(0);
    collapsingToolbarLayout.setLayoutParams(p);
}

to disable the collapsing behavior (works well), and finally this:

@Override
public void hide() {
    final AppBarLayout layout = (AppBarLayout) findViewById(R.id.appbar);

    layout.animate().translationY(-layout.getHeight())
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    layout.setVisibility(View.GONE);
                }
            }).start();
}

I make the AppBarLayout translate to the top (works smoothly), and at the end of the animation set is visibility to View.GONE.

Issue

At the end of the animation, no matter I also set the visibility to GONE, I can't get the space that was previously occupied by the AppBarLayout. My NestedScrollView remains confined in the lower half of the screen, as if the AppBarLayout was still there (which is not). How can I fix it?

Before hiding:

Before

After hiding (AppBar translated to the top):

After

As you can see, the top space is empty and unreachable. The scroll view scrolls inside the margins it had before, as if the visibility change was not measured by the CoordinatorLayout.

  • I have tried calling coordinator.requestLayout(), with no success.

  • I also tried setting the AppBarLayout as an app:anchor for my NestedScrollView, but that screws things up - scroll view ends up taking the whole screen even before hiding.

  • I was thinking of a custom Behavior to be set on the scroll view when entering this hidden-AppBar mode, but I can't get started on that.

Answer

Alberto Polo picture Alberto Polo · Nov 11, 2015

Yes this looks like a bug, I solved this issue for my application setting the appbar height to 0:

android.support.design.widget.AppBarLayout appbar = (android.support.design.widget.AppBarLayout) findViewById(R.id.appbar);

CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams)appbar.getLayoutParams();

lp.height = 0;

appbar.setLayoutParams(lp);