I have a LinearLayout
that I want to show or hide with an Animation
that pushes the layout upwards or downwards whenever I change its visibility.
I've seen a few samples out there but none of them suit my needs.
I have created two xml files for the animations but I do not know how to start them when I change the visibility of a LinearLayout
.
With the new animation API that was introduced in Android 3.0 (Honeycomb) it is very simple to create such animations.
Sliding a
View
down by a distance:You can later slide the
View
back to its original position like this:You can also easily combine multiple animations. The following animation will slide a
View
down by its height and fade it in at the same time:You can then fade the
View
back out and slide it back to its original position. We also set anAnimatorListener
so we can set the visibility of theView
back toGONE
once the animation is finished:I had a corner case where my view's height was still
zero
so...Suragch's answer in Kotlin. This worked for me.
}
Using ObjectAnimator
You can start the correct
Animation
when the visibility of theLinearLayout
changes by creating a new subclass ofLinearLayout
and overridingsetVisibility()
to start theAnimations
. Consider something like this:Easiest solution: set
android:animateLayoutChanges="true"
on the container holding your views.To put it into some context: If you have a layout like below, all visibility changes to the views in this container will be animated automatically.
You can find more details about this on Animating Layout Changes - Android Developer