Let's say I have a vertical linearLayout with :
[v1]
[v2]
By default v1 has visibily = GONE. I would like to show v1 with an expand animation and push down v2 at the same time.
I tried something like this:
Animation a = new Animation()
{
int initialHeight;
@Override
protected void applyTransformation(float interpolatedTime, Transformation t) {
final int newHeight = (int)(initialHeight * interpolatedTime);
v.getLayoutParams().height = newHeight;
v.requestLayout();
}
@Override
public void initialize(int width, int height, int parentWidth, int parentHeight) {
super.initialize(width, height, parentWidth, parentHeight);
initialHeight = height;
}
@Override
public boolean willChangeBounds() {
return true;
}
};
But with this solution, I have a blink when the animation starts. I think it's caused by v1 displaying full size before the animation is applied.
With javascript, this is one line of jQuery! Any simple way to do this with android?
I think the easiest solution is to set
android:animateLayoutChanges="true"
to yourLinearLayout
and then just show/hide view by seting its visibility. Works like a charm, but you have no controll on the animation durationUse ValueAnimator:
An alternative is to use a scale animation with the following scaling factors for expanding:
and for collapsing:
Yes, I agreed with the above comments. And indeed, it does seem like the right (or at least the easiest?) thing to do is to specify (in XML) an initial layout height of "0px" -- and then you can pass in another argument for "toHeight" (i.e. the "final height") to the constructor of your custom Animation sub-class, e.g. in the example above, it would look something like so:
Anyways, hope that helps! :)
I adapted the currently accepted answer by Tom Esterez, which worked but had a choppy and not very smooth animation. My solution basically replaces the
Animation
with aValueAnimator
, which can be fitted with anInterpolator
of your choice to achieve various effects such as overshoot, bounce, accelerate, etc.This solution works great with views that have a dynamic height (i.e. using
WRAP_CONTENT
), as it first measures the actual required height and then animates to that height.You then simply call
expand( myView );
orcollapse( myView );
.