4

I tried to animate a switch-color on CardView background, but I'm getting this:

Cannot resolve method 'setCardBackgroundColor(android.graphics.drawable.TransitionDrawable)'

If CardView does not support TransitionDrawable, then how can we achieve something like this?

public void setCardBackground(CardView cardView) {
    ColorDrawable[] color = {new ColorDrawable(Color.BLUE), new ColorDrawable(Color.RED)};
    TransitionDrawable trans = new TransitionDrawable(color);
     //cardView.setCardBackgroundColor(trans);
    trans.startTransition(5000);
}
azizbekian
  • 60,783
  • 13
  • 169
  • 249
S.R
  • 2,819
  • 2
  • 22
  • 49

2 Answers2

2

Have you tried View#setBackground()?

public void setCardBackground(CardView cardView) {
    ColorDrawable[] color = {new ColorDrawable(Color.BLUE), new ColorDrawable(Color.RED)};
    TransitionDrawable trans = new TransitionDrawable(color);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.ICE_CREAM_SANDWICH_MR1) {
        cardView.setBackground(trans);
    } else {
        cardView.setBackgroundDrawable(trans);
    }
    trans.startTransition(5000);
}
azizbekian
  • 60,783
  • 13
  • 169
  • 249
1

The answer by azizbekian will break rounded corners of the CardView. To set the background color of one, you should use the CardView-specific method setCardBackgroundColor.

Here is a solution that preserves them:

Kotlin

fun setCardBackground(cardView: CardView) {
    val colors = intArrayOf(Color.BLACK, Color.RED)
    ValueAnimator.ofArgb(*colors).apply {
        duration = 5000
        addUpdateListener {
            cardView.setCardBackgroundColor(it.animatedValue as Int)
        }
        start()
    }
}

Java

public void setCardBackground(CardView cardView) {
    int[] colors = {Color.BLACK, Color.RED};
    ValueAnimator animator = ValueAnimator.ofArgb(colors);
    animator.setDuration(5000);
    animator.addUpdateListener(animation ->
            cardView.setCardBackgroundColor(((int) animator.getAnimatedValue()))
    );
    animator.start();
}
Nohus
  • 739
  • 8
  • 16