12

I want to programmatically hide / show the TabLayout in my AppBarLayout. Simply setting visibility to VISIBLE and GONE is not enough, as I want to animate the changes and reclaim the space with my content while the tab retreats and leave the space once the tab is shown back.

Below is the relevant part of my layout XML -

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

        <android.support.design.widget.TabLayout
            android:id="@android:id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:layout_scrollFlags="scroll|enterAlways"
            app:tabMode="scrollable"
            android:layout_marginStart="42dp"
            android:layout_marginLeft="42dp"
            style="@style/MainTabLayout">

        </android.support.design.widget.TabLayout>
    </android.support.design.widget.AppBarLayout>
jaibatrik
  • 6,770
  • 9
  • 33
  • 62
  • To animate the change, just add android:animateLayoutChanges="true" to the parent AppBarLayout. That said, View.GONE should be enough. – natario Sep 13 '15 at 13:37
  • That works seamlessly! Thanks! If you could post it as answer, I'll be able to accept it. – jaibatrik Sep 13 '15 at 14:25

1 Answers1

20

As any ViewGroup subclass, AppBarLayout allows for automatic animations during the adding/removal of child views. You just need to add android:animateLayoutChanges="true" (default to false) in your layout file.

As for reclaiming the space content when the view is gone, all you have to do is use setVisibility(View.GONE) rather than setVisibility(View.INVISIBLE), because the latter holds the space for the invisible view.

natario
  • 24,954
  • 17
  • 88
  • 158