Android上视图背景颜色的动画变化

Android上视图背景颜色的动画变化

本文介绍了Android上视图背景颜色的动画变化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您如何在 Android 上为视图背景颜色的变化设置动画?

How do you animate the change of background color of a view on Android?

例如:

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

I have a view with a red background color. The background color of the view changes to blue. How can I do a smooth transition between colors?

如果使用视图无法做到这一点,欢迎使用替代方法.

If this can't be done with views, an alternative will be welcome.

推荐答案

我最终找到了一个(相当不错的)解决方案!

I ended up figuring out a (pretty good) solution for this problem!

您可以使用 TransitionDrawable 来实现这一点.例如,在 drawable 文件夹中的 XML 文件中,您可以编写如下内容:

You can use a TransitionDrawable to accomplish this. For example, in an XML file in the drawable folder you could write something like:

<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
    <item android:drawable="@drawable/original_state" />
    <item android:drawable="@drawable/new_state" />
</transition>

然后,在实际视图的 XML 中,您将在 android:background 属性中引用此 TransitionDrawable.

Then, in your XML for the actual View you would reference this TransitionDrawable in the android:background attribute.

此时,您可以通过执行以下操作在代码中启动转换:

At this point you can initiate the transition in your code on-command by doing:

TransitionDrawable transition = (TransitionDrawable) viewObj.getBackground();
transition.startTransition(transitionTime);

或者通过调用反向运行转换:

Or run the transition in reverse by calling:

transition.reverseTransition(transitionTime);

请参阅 Roman 的回答,了解使用 Property Animation API 的另一种解决方案,该解决方案在此答案发布时不可用最初发布.


See Roman's answer for another solution using the Property Animation API, which wasn't available at the time this answer was originally posted.

这篇关于Android上视图背景颜色的动画变化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 10:33