你如何为Android上视图的背景颜色变化设置动画?
例如:
我有一个红色背景颜色的视图。视图的背景颜色变为蓝色。如何在颜色之间进行平滑过渡?
如果这不能通过视图来完成,那么欢迎使用替代方法。
你如何为Android上视图的背景颜色变化设置动画?
例如:
我有一个红色背景颜色的视图。视图的背景颜色变为蓝色。如何在颜色之间进行平滑过渡?
如果这不能通过视图来完成,那么欢迎使用替代方法。
您可以使用新的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,请使用来自 Jake Wharton 的九个旧 Android 库。
该getColor
方法在 Android M 中已弃用,因此您有两种选择:
如果您使用支持库,则需要将getColor
调用替换为:
ContextCompat.getColor(this, R.color.red);
如果您不使用支持库,则需要将getColor
调用替换为:
getColor(R.color.red);
我最终为这个问题找到了一个(相当不错的)解决方案!
您可以使用TransitionDrawable来完成此操作。例如,在可绘制文件夹中的 XML 文件中,您可以编写如下内容:
<?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>
然后,在实际 View 的 XML 中,您将在android:background
属性中引用此 TransitionDrawable。
此时,您可以通过执行以下操作在您的代码命令中启动转换:
TransitionDrawable transition = (TransitionDrawable) viewObj.getBackground();
transition.startTransition(transitionTime);
或者通过调用反向运行转换:
transition.reverseTransition(transitionTime);
有关使用 Property Animation API 的另一种解决方案,请参阅Roman 的答案,该答案在最初发布此答案时不可用。
根据您的视图如何获得其背景颜色以及您如何获得目标颜色,有几种不同的方法可以做到这一点。
前两个使用Android 属性动画框架。
在以下情况下使用对象动画师:
argb
xml 文件中的值。view.setBackgroundColor()
对象动画师通过调用view.setBackgroundColor
which 替换定义的可绘制对象来工作,除非它是 a 的实例ColorDrawable
,但它很少是。这意味着来自可绘制对象的任何额外背景属性(如笔划或角)都将被删除。
在以下情况下使用Value Animator:
在以下情况下使用过渡可绘制对象:
我在打开一个我无法解决的 DrawerLayout 时运行的 Transition drawables 遇到了一些性能问题,所以如果您遇到任何意外的口吃,您可能会遇到与我相同的错误。
如果要使用StateLists drawable或LayerLists drawable ,则必须修改 Value Animator 示例,否则它将final GradientDrawable background = (GradientDrawable) view.getBackground();
在线崩溃。
查看定义:
<View
android:background="#FFFF0000"
android:layout_width="50dp"
android:layout_height="50dp"/>
创建和使用ObjectAnimator
这样的。
final ObjectAnimator backgroundColorAnimator = ObjectAnimator.ofObject(view,
"backgroundColor",
new ArgbEvaluator(),
0xFFFFFFFF,
0xff78c5f9);
backgroundColorAnimator.setDuration(300);
backgroundColorAnimator.start();
您还可以使用 AnimatorInflater 从 xml 加载动画定义,就像 XMight 在Android objectAnimator animate backgroundColor of Layout
查看定义:
<View
android:background="@drawable/example"
android:layout_width="50dp"
android:layout_height="50dp"/>
可绘制定义:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#FFFFFF"/>
<stroke
android:color="#edf0f6"
android:width="1dp"/>
<corners android:radius="3dp"/>
</shape>
像这样创建和使用 ValueAnimator:
final ValueAnimator valueAnimator = ValueAnimator.ofObject(new ArgbEvaluator(),
0xFFFFFFFF,
0xff78c5f9);
final GradientDrawable background = (GradientDrawable) view.getBackground();
currentAnimation.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(final ValueAnimator animator) {
background.setColor((Integer) animator.getAnimatedValue());
}
});
currentAnimation.setDuration(300);
currentAnimation.start();
查看定义:
<View
android:background="@drawable/example"
android:layout_width="50dp"
android:layout_height="50dp"/>
可绘制定义:
<?xml version="1.0" encoding="utf-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<solid android:color="#FFFFFF"/>
<stroke
android:color="#edf0f6"
android:width="1dp"/>
<corners android:radius="3dp"/>
</shape>
</item>
<item>
<shape>
<solid android:color="#78c5f9"/>
<stroke
android:color="#68aff4"
android:width="1dp"/>
<corners android:radius="3dp"/>
</shape>
</item>
</transition>
像这样使用 TransitionDrawable:
final TransitionDrawable background = (TransitionDrawable) view.getBackground();
background.startTransition(300);
您可以通过调用.reverse()
动画实例来反转动画。
还有其他一些制作动画的方法,但这三种可能是最常见的。我通常使用 ValueAnimator。
您可以制作对象动画师。例如,我有一个 targetView,我想改变你的背景颜色:
int colorFrom = Color.RED;
int colorTo = Color.GREEN;
int duration = 1000;
ObjectAnimator.ofObject(targetView, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo)
.setDuration(duration)
.start();
如果你想要这样的彩色动画,
此代码将帮助您:
ValueAnimator anim = ValueAnimator.ofFloat(0, 1);
anim.setDuration(2000);
float[] hsv;
int runColor;
int hue = 0;
hsv = new float[3]; // Transition color
hsv[1] = 1;
hsv[2] = 1;
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
hsv[0] = 360 * animation.getAnimatedFraction();
runColor = Color.HSVToColor(hsv);
yourView.setBackgroundColor(runColor);
}
});
anim.setRepeatCount(Animation.INFINITE);
anim.start();
最好的方法是使用ValueAnimator和ColorUtils.blendARGB
ValueAnimator valueAnimator = ValueAnimator.ofFloat(0.0f, 1.0f);
valueAnimator.setDuration(325);
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float fractionAnim = (float) valueAnimator.getAnimatedValue();
view.setBackgroundColor(ColorUtils.blendARGB(Color.parseColor("#FFFFFF")
, Color.parseColor("#000000")
, fractionAnim));
}
});
valueAnimator.start();
XML 驱动动画的文档很糟糕。我已经搜索了大约几个小时,只是为了在按下按钮时为按钮的背景颜色设置动画......可悲的是,动画只有一个属性:您可以exitFadeDuration
在selector
:
<selector xmlns:android="http://schemas.android.com/apk/res/android"
android:exitFadeDuration="200">
<item android:state_pressed="true">
<shape android:tint="#3F51B5" />
</item>
<item>
<shape android:tint="#F44336" />
</item>
</selector>
然后将其用作background
您的视图。不需要 Java/Kotlin 代码。
实现此目的的另一种简单方法是使用 AlphaAnimation 执行淡入淡出。
这是我在 Base Activity 中用来更改背景的方法。我正在使用代码中生成的 GradientDrawables,但可以进行调整以适应。
protected void setPageBackground(View root, int type){
if (root!=null) {
Drawable currentBG = root.getBackground();
//add your own logic here to determine the newBG
Drawable newBG = Utils.createGradientDrawable(type);
if (currentBG==null) {
if(Build.VERSION.SDK_INT<Build.VERSION_CODES.JELLY_BEAN){
root.setBackgroundDrawable(newBG);
}else{
root.setBackground(newBG);
}
}else{
TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{currentBG, newBG});
transitionDrawable.setCrossFadeEnabled(true);
if(Build.VERSION.SDK_INT<Build.VERSION_CODES.JELLY_BEAN){
root.setBackgroundDrawable(transitionDrawable);
}else{
root.setBackground(transitionDrawable);
}
transitionDrawable.startTransition(400);
}
}
}
更新:如果有人遇到我发现的相同问题,出于某种原因,在 Android <4.3 上使用setCrossFadeEnabled(true)
会导致不希望的白化效果,因此我不得不使用上面提到的@Roman Minenok ValueAnimator 方法切换到 <4.3 的纯色。
这是一个很好的功能,它允许这样做:
public static void animateBetweenColors(final @NonNull View viewToAnimateItsBackground, final int colorFrom,
final int colorTo, final int durationInMs) {
final ColorDrawable colorDrawable = new ColorDrawable(durationInMs > 0 ? colorFrom : colorTo);
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable);
if (durationInMs > 0) {
final ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(animator -> {
colorDrawable.setColor((Integer) animator.getAnimatedValue());
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable);
});
colorAnimation.setDuration(durationInMs);
colorAnimation.start();
}
}
在 Kotlin 中:
@JvmStatic
fun animateBetweenColors(viewToAnimateItsBackground: View, colorFrom: Int, colorTo: Int, durationInMs: Int) {
val colorDrawable = ColorDrawable(if (durationInMs > 0) colorFrom else colorTo)
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable)
if (durationInMs > 0) {
val colorAnimation = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
colorAnimation.addUpdateListener { animator: ValueAnimator ->
colorDrawable.color = (animator.animatedValue as Int)
ViewCompat.setBackground(viewToAnimateItsBackground, colorDrawable)
}
colorAnimation.duration = durationInMs.toLong()
colorAnimation.start()
}
}
答案以多种方式给出。您还可以使用ofArgb(startColor,endColor)
.ValueAnimator
对于 API > 21:
int cyanColorBg = ContextCompat.getColor(this,R.color.cyan_bg);
int purpleColorBg = ContextCompat.getColor(this,R.color.purple_bg);
ValueAnimator valueAnimator = ValueAnimator.ofArgb(cyanColorBg,purpleColorBg);
valueAnimator.setDuration(500);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
relativeLayout.setBackgroundColor((Integer)valueAnimator.getAnimatedValue());
}
});
valueAnimator.start();
对 Kotlin 使用以下函数:
private fun animateColorValue(view: View) {
val colorAnimation =
ValueAnimator.ofObject(ArgbEvaluator(), Color.GRAY, Color.CYAN)
colorAnimation.duration = 500L
colorAnimation.addUpdateListener { animator -> view.setBackgroundColor(animator.animatedValue as Int) }
colorAnimation.start()
}
传递您想要更改颜色的任何视图。
将文件夹动画师添加到res文件夹中。(名称必须是animator)。添加动画器资源文件。例如res/animator/fade.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
<objectAnimator
android:propertyName="backgroundColor"
android:duration="1000"
android:valueFrom="#000000"
android:valueTo="#FFFFFF"
android:startOffset="0"
android:repeatCount="-1"
android:repeatMode="reverse" />
</set>
在 Activity java 文件中,调用它
View v = getWindow().getDecorView().findViewById(android.R.id.content);
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.fade);
set.setTarget(v);
set.start();
我发现ArgbEvaluator
Android 源代码中使用的实现在转换颜色方面做得最好。使用 HSV 时,根据这两种颜色,过渡对我来说跳过了太多的色调。但是这个方法不行。
如果您想简单地制作动画,请按照此处的建议使用ArgbEvaluator
with :ValueAnimator
ValueAnimator colorAnimation = ValueAnimator.ofObject(new ArgbEvaluator(), colorFrom, colorTo);
colorAnimation.addUpdateListener(new AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animator) {
view.setBackgroundColor((int) animator.getAnimatedValue());
}
});
colorAnimation.start();
但是,如果您像我一样想要将您的过渡与某些用户手势或从输入传递的其他值联系起来,ValueAnimator
则没有太大帮助(除非您的目标是 API 22 及更高版本,在这种情况下您可以使用该ValueAnimator.setCurrentFraction()
方法)。ArgbEvaluator
当目标低于 API 22 时,将源代码中的代码包装在您自己的方法中,如下所示:
public static int interpolateColor(float fraction, int startValue, int endValue) {
int startA = (startValue >> 24) & 0xff;
int startR = (startValue >> 16) & 0xff;
int startG = (startValue >> 8) & 0xff;
int startB = startValue & 0xff;
int endA = (endValue >> 24) & 0xff;
int endR = (endValue >> 16) & 0xff;
int endG = (endValue >> 8) & 0xff;
int endB = endValue & 0xff;
return ((startA + (int) (fraction * (endA - startA))) << 24) |
((startR + (int) (fraction * (endR - startR))) << 16) |
((startG + (int) (fraction * (endG - startG))) << 8) |
((startB + (int) (fraction * (endB - startB))));
}
并随心所欲地使用它。
您可以像这样使用ValueAnimator:
fun startColorAnimation(v: View) {
val colorStart = v.solidColor
val colorEnd = Color.RED
val colorAnim: ValueAnimator = ObjectAnimator.ofInt(v, "backgroundColor", colorStart, colorEnd)
colorAnim.setDuration(1000)
colorAnim.setEvaluator(ArgbEvaluator())
colorAnim.repeatCount = 1
colorAnim.repeatMode = ValueAnimator.REVERSE
colorAnim.start()
}
Roman Minenok在 kotlin 中回答并作为扩展功能
fun View.colorTransition(@ColorRes startColor: Int, @ColorRes endColor: Int, duration: Long = 250L){
val colorFrom = ContextCompat.getColor(context, startColor)
val colorTo = ContextCompat.getColor(context, endColor)
val colorAnimation: ValueAnimator = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
colorAnimation.duration = duration
colorAnimation.addUpdateListener {
if (it.animatedValue is Int) {
val color=it.animatedValue as Int
setBackgroundColor(color)
}
}
colorAnimation.start()
}
如果您想从当前背景颜色更改为新颜色,那么您可以使用它
fun View.colorTransition(@ColorRes endColor: Int, duration: Long = 250L){
var colorFrom = Color.TRANSPARENT
if (background is ColorDrawable)
colorFrom = (background as ColorDrawable).color
val colorTo = ContextCompat.getcolor(context, endColor)
val colorAnimation: ValueAnimator = ValueAnimator.ofObject(ArgbEvaluator(), colorFrom, colorTo)
colorAnimation.duration = duration
colorAnimation.addUpdateListener {
if (it.animatedValue is Int) {
val color=it.animatedValue as Int
setBackgroundColor(color)
}
}
colorAnimation.start()
}
用法
myView.colorTransition(R.color.bg_color)
根据ademar111190 的回答,我创建了这个方法,它将在任何两种颜色之间脉冲视图的背景颜色:
private void animateBackground(View view, int colorFrom, int colorTo, int duration) {
ObjectAnimator objectAnimator = ObjectAnimator.ofObject(view, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo);
objectAnimator.setDuration(duration);
//objectAnimator.setRepeatCount(Animation.INFINITE);
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
// Call this method again, but with the two colors switched around.
animateBackground(view, colorTo, colorFrom, duration);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
objectAnimator.start();
}
您可以使用API 11 以上的ArgbEvaluatorCompat类。
implementation 'com.google.android.material:material:1.0.0'
ValueAnimator colorAnim = ValueAnimator.ofObject(new ArgbEvaluatorCompat(), startColor, endColor);
colorAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
mTargetColor = (int) animation.getAnimatedValue();
}
});
colorAnim.start();