Programmatically hide / show android support design TabLayout inside AppBarLayout
M

1

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>
Moil answered 13/9, 2015 at 13:21 Comment(2)
To animate the change, just add android:animateLayoutChanges="true" to the parent AppBarLayout. That said, View.GONE should be enough.Anagrammatize
That works seamlessly! Thanks! If you could post it as answer, I'll be able to accept it.Moil
A
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.

Anagrammatize answered 13/9, 2015 at 15:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.