如何在Android中创建平滑的高度变化动画

时间:2018-08-03 13:13:16

标签: java android animation android-animation

我想创建高度变化的平滑动画。在下面,您可以看到我当前的实现。它可以工作,但不像我期望的那样平滑。

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
     private final int targetHeight;
     private final View view;
     private final int height;

     public HeightAnimation(View view, int targetHeight) {
         this.view = view;
         this.targetHeight = targetHeight;
         height = view.getHeight();
     }

     @Override
     protected void applyTransformation(float interpolatedTime, Transformation t) {
         view.getLayoutParams().height = (int) (height + (targetHeight - height) * interpolatedTime);
         view.requestLayout();
     }

     @Override
     public void initialize(int width, int height, int parentWidth,
                       int parentHeight) {
         super.initialize(width, height, parentWidth, parentHeight);
     }

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

有人对此有更好的解决方案吗?也许有一种使用ObjectAnimator的方法?

2 个答案:

答案 0 :(得分:0)

我认为您应该使用Animation来驱动它,而不是创建扩展ObjectAnimator的类。

private void animateViewHeight(View view, int targetHeight) {
    ValueAnimator animator = ObjectAnimator.ofInt(view.getHeight(), targetHeight);

    animator.addUpdateListener(animation -> {
        LayoutParams params = view.getLayoutParams();
        params.height = (int) animation.getAnimatedValue();
        view.setLayoutParams(params);
    });

    animator.start();
}

答案 1 :(得分:0)

有一个简单的方法 而且足够平滑

view.clearAnimation();
view.animate().translateY(150);

退回到上一个位置

view.clearAnimation();
view.animate().translateY(0);