如何在 Android 上以动画方式改变视图的背景颜色?
例如:
我有一个背景色为红色的视图。视图的背景颜色更改为蓝色。如何在颜色之间实现平滑过渡?
如果无法通过视图来完成此操作,则欢迎使用替代方案。
您可以使用新的属性动画 API http://developer.android.com/guide/topics/graphics/prop-animation.html对于彩色动画:
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 使用九个老机器人库 http://nineoldandroids.com/来自杰克·沃顿。
The getColor
该方法在 Android M 中已被弃用,因此您有两种选择:
-
如果使用support库,则需要替换getColor
呼叫:
ContextCompat.getColor(this, R.color.red);
-
如果不使用支持库,则需要替换getColor
呼叫:
getColor(R.color.red);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)