如何在android中的CardView(即SlideUp& SlideDown)中为布局设置动画

时间:2015-02-28 08:31:31

标签: android android-animation material-design

我有一个RelativeLayout,其可见性gone包含3个操作按钮。我希望在单击下拉图像时将此布局设置为SlideUp和SlideDown的动画。

enter image description here

1 个答案:

答案 0 :(得分:0)

这是一个可以为您执行此操作的实用程序类:

public class AnimExpandCollapse {

public static void expand(final View v) {
    v.measure( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT );
    final int targetHeight = v.getMeasuredHeight();

    v.getLayoutParams().height = 0;
    v.setVisibility(View.VISIBLE);
    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            v.getLayoutParams().height = interpolatedTime == 1
                    ? LayoutParams.WRAP_CONTENT
                    : (int)(targetHeight * interpolatedTime);
            v.requestLayout();
        }
        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    a.setDuration((int)(targetHeight / v.getContext().getResources().getDisplayMetrics().density));
    v.startAnimation(a);
}

public static void setViewToWrappedHeight(View v) {
    v.getLayoutParams().height = LayoutParams.WRAP_CONTENT;
}

public static void collapse(final View v) {
    collapse(v, null, true, 0);
}

public static void collapse(final View v, Animation.AnimationListener animationListener, boolean autoDuration, int duration) {

    final int initialHeight = v.getMeasuredHeight();

    Animation a = new Animation()
    {
        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            if (interpolatedTime == 1){
                v.setVisibility(View.GONE);
            } else {
                v.getLayoutParams().height = initialHeight - (int)(initialHeight * interpolatedTime);
                v.requestLayout();
            }
        }

        @Override
        public boolean willChangeBounds() {
            return true;
        }
    };

    // 1dp/ms
    if (autoDuration) {
        a.setDuration((int)(initialHeight / v.getContext().getResources().getDisplayMetrics().density));
    } else {
        a.setDuration(duration);
    }
    if (animationListener!=null) a.setAnimationListener(animationListener);
    v.startAnimation(a);
}}