OGeek|极客世界-中国程序员成长平台

标题: android - Android上 View 背景颜色的动画变化 [打印本页]

作者: 菜鸟教程小白    时间: 2022-8-1 01:19
标题: android - Android上 View 背景颜色的动画变化

你如何为Android上 View 的背景颜色变化设置动画?

例如:

我有一个红色背景颜色的 View 。 View 的背景颜色变为蓝色。如何在颜色之间进行平滑过渡?

如果这不能通过 View 来完成,那么欢迎使用替代方法。



Best Answer-推荐答案


您可以使用新的 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/






    欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://jike.in/) Powered by Discuz! X3.4