如何在 Android 上为 View 的背景颜色变化设置动画?
例如:
我有一个红色背景色的 View 。 View 的背景颜色变为蓝色。如何在颜色之间进行平滑过渡?
如果 View 无法做到这一点,欢迎使用替代方法。
最佳答案
您可以使用新的 Property Animation Api彩色动画:
int colorFrom = getResources().getColor(R.color.red);
int colorTo = getResources().getColor(R.color.blue);
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.setDuration(250); // milliseconds
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
textView.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
为了向后兼容 Android 2.x,请使用 Nine Old Androids library来自 jack 沃顿。
getColor
方法在 Android M 中已弃用,因此您有两种选择:
如果您使用支持库,则需要将
getColor
调用替换为:ContextCompat.getColor(this, R.color.red);
如果您不使用支持库,则需要将
getColor
调用替换为:getColor(R.color.red);
关于android - Android上 View 背景颜色的动画变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2614545/