4

我试图在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);
}
4

2 回答 2

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);
}
于 2017-06-12T05:44:23.430 回答
0

azizbekian 的回答将打破 CardView 的圆角。要设置一个的背景颜色,您应该使用 CardView-specific 方法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()
    }
}

爪哇

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();
}
于 2021-02-24T12:27:07.167 回答