expand Animation - Android Animation

Android examples for Animation:Expand Animation

Description

expand Animation

Demo Code


//package com.java2s;
import java.lang.reflect.Method;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class Main {

    public static Animation expandAnimation(final View v,
            final boolean expand, int duration) {
        try {//  www.j  a va  2s  .  c  om
            Method m = v.getClass().getDeclaredMethod("onMeasure",
                    int.class, int.class);
            m.setAccessible(true);
            m.invoke(v, MeasureSpec.makeMeasureSpec(0,
                    MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(
                    ((View) v.getParent()).getMeasuredWidth(),
                    MeasureSpec.AT_MOST));
        } catch (Exception e) {
            e.printStackTrace();
        }

        final int initialHeight = v.getMeasuredHeight();

        if (expand) {
            v.getLayoutParams().height = 0;
        } else {
            v.getLayoutParams().height = initialHeight;
        }
        v.setVisibility(View.VISIBLE);

        Animation a = new Animation() {
            protected void applyTransformation(float interpolatedTime,
                    Transformation t) {
                int newHeight = 0;
                if (expand) {
                    newHeight = (int) (initialHeight * interpolatedTime);
                } else {
                    newHeight = (int) (initialHeight * (1 - interpolatedTime));
                }
                v.getLayoutParams().height = newHeight;
                v.requestLayout();

                if (interpolatedTime == 1 && !expand)
                    v.setVisibility(View.GONE);
            }

            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        a.setDuration(duration);

        return a;
    }
}

Related Tutorials