Search code examples
androidandroid-layoutandroid-animationandroid-coordinatorlayoutandroid-appbarlayout

Animating views in AppBarLayout


I have an AppBarLayout inside a coordinatorLayout as follows:

<coordinatorLayout>
<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.widget.TabLayout
        android:id="@+id/scrollable_category_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_scrollFlags="scroll|enterAlways|snap"
        app:tabGravity="center"
        app:tabMode="scrollable" />

    <RelativeLayout
        android:id="@+id/parent_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="100dp"
        android:background="@android:color/white"
        android:visibility="visible">

        <few more layout/>
    </RelativeLayout>
</android.support.design.widget.AppBarLayout>

<more views>
</coordinatorLayout>

I want the relativeLayout to be hidden by default and if the API gives a particular response then I will show the RelativeLayout with its content. The content can have varying height depending on the API response (eg. Text can be single line or multiline etc.). So I dont know the height of the view in the begining. Now I want to apply a translationY to the view such that it appears to be coming from beneath the tabLayout (showing shadows etc.).

I have tried many solutions, one of which is:

adParentLayout.animate()
.translationY(0)
.setDuration(5000)
.withEndAction(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, "Animation Complete", Toast.LENGTH_SHORT).show();
        }
    })
.withStartAction(new Runnable() {
        @Override
        public void run() {
            adParentLayout.setVisibility(View.VISIBLE);
            adParentLayout.setTranslationY(-adParentLayout.getHeight());
        }
    });

This obviously doesn't work. I dont know much about animations and would like suggestions.

One solution I tried was making the view visible in the layout and then apply translation. But this makes the view translate above the TabLayout covering it completely. It turns out that AppBarLayout extends LinearLayout, so the second Layout RelativeLayout translated above it. I dont understand how this effect can be achieved and any input in the right direction will be helpful.


Solution

  • I got it working with LayoutTransition. Basically I just added android:animateLayoutchanges=true in appBarLayout and it handled animating the visibility of the view.

    I didnt know about this. Seems like a great thing to have.