【问题标题】:CardView doesn't support TransitionDrawable?CardView 不支持 TransitionDrawable?
【发布时间】:2017-06-09 14:16:00
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    你试过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);
    }
    

    【讨论】:

    • 这不能正常工作。它打破了 CardView 上的圆角。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-02-15
      • 2015-02-10
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 2017-07-07
      • 1970-01-01
      • 2011-08-31
      • 2016-07-18
      相关资源
      最近更新 更多