问题描述
允许用户使用滑块沿 Y 轴更改屏幕上的按钮位置。发生这种情况时,我想为我的 Button 设置动画。例如,View 位于 (0,0),用户突然将其位置设置为 (0,420)。
按钮应该首先淡出(在 400 毫秒内从 alpha 1.0 到 alpha 0.0),同时位于当前位置 (0,0)。
然后,按钮位置应更改为 (0,420),并且应在位于更改后的位置 (0,420) 时淡入(在 400 毫秒内从 alpha 0.0 到 alpha 1.0)。
由于 Button 位置可以很快改变,所以我得到的是一个华而不实的动画效果,这是我不想要的。 这是我的代码:
/* Alpha from 1 to 0 */
ObjectAnimator animation = ObjectAnimator.ofFloat(myButton,"alpha",1,0);
animation.setDuration(400);
animation.setRepeatCount(1);
animation.setInterpolator(new LinearInterpolator());
animation.start();
/* Alpha from 0 back to 1 */
animation = ObjectAnimator.ofFloat(myButton,1);
animation.setDuration(400);
animation.setRepeatCount(1);
animation.setInterpolator(new LinearInterpolator());
animation.start();
解决方法
我使用 ValueAnimator 找到了解决方案:
ValueAnimator animator = ValueAnimator.ofInt((int) oldY,newY);
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
params.y = (Integer) animation.getAnimatedValue();
mWindowManager.updateViewLayout(myView,params);
}
});
animator.start();