CardView不支持TransitionDrawable吗?

时间:2017-06-09 14:16:01

标签: java android android-animation android-cardview transitiondrawable

我尝试在CardView背景上设置开关颜色的动画,但我得到了这个:

  

无法解析方法' setCardBackgroundColor(android.graphics.drawable.TransitionDrawable)'

如果CardView不支持TransitionDrawable,那么我们怎样才能实现这样的目标呢?

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);
}

2 个答案:

答案 0 :(得分:2)

您是否尝试过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);
}

答案 1 :(得分:0)

azizbekian 的回答将打破 CardView 的圆角。要设置一个的背景颜色,您应该使用 CardView 特定的方法 setCardBackgroundColor

这是一个保留它们的解决方案:

科特林

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();
}