问题描述
如何在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!
您可以使用即可实现。例如,在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中获取实际的View,您可以在 android:background 属性。
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);
请参见,该解决方案最初发布时尚不可用。
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上对视图背景颜色进行动画处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!