安卓(Android) 怎么展开动画(Animation)

2019年10月15日20:33:02安卓(Android) 怎么展开动画(Animation)已关闭评论 286 1243字阅读4分8秒

1.简介

安卓(Android) 怎么展开动画(Animation)?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */


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 {
            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;
    }
}

 
继续阅读
编程十万个怎么办