如何在Android中为LayoutParams x和y制作动画

时间:2015-03-23 14:37:53

标签: android android-animation

我是android新手。 我有以下代码:

// layoutParams of type WindowManager.LayoutParams
layoutParams.x = someX;
layoutParams.y = someY;
windowManager.updateViewLayout(someView, layoutParams);

如何设置此更改的动画?像翻译一样...

2 个答案:

答案 0 :(得分:2)

您可以使用ValueAnimator

int beginValue = 0;
int endValue = 100;

ValueAnimator animator = ValueAnimator.ofInt(beginValue, endValue);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        WindowManager.LayoutParams layoutParams =
                (WindowManager.LayoutParams) view.getLayoutParams();
        layoutParams.x = (Integer) animation.getAnimatedValue();
        layoutParams.y = (Integer) animation.getAnimatedValue();
        getWindowManager().updateViewLayout(view, params);
    }
});
animator.start();

答案 1 :(得分:0)

在x和y之间进行动画制作时使用属性值持有者。

public void animate(final View v, int startX, int endX, int startY, int endY) {

    PropertyValuesHolder pvhX = PropertyValuesHolder.ofInt("x", startX, endX);
    PropertyValuesHolder pvhY = PropertyValuesHolder.ofInt("y", startY, endY);

    ValueAnimator translator = ValueAnimator.ofPropertyValuesHolder(pvhX, pvhY);

    translator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator valueAnimator) {
            WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) v.getLayoutParams();
            layoutParams.x = (Integer) valueAnimator.getAnimatedValue("x");
            layoutParams.y = (Integer) valueAnimator.getAnimatedValue("y");
            windowManager.updateViewLayout(v, layoutParams);
        }
    });

    translator.setDuration(100);
    translator.start();
}