Android 当 API <21 时,CardView 将背景设置为 BitmapDrawable

Android CardView setBackground as BitmapDrawable when API <21

当我尝试在 KitKat.When 中以编程方式对 CardView 进行 setBackground() 时遇到问题,应用程序在 Android 上 运行 L 有我的代码没问题:

Drawable drawable = new BitmapDrawable(appContext.getResources(), bitmap);
if (cardView != null) {                
    cardView.setBackground(drawable);
}

但是当它在 API 早于 Android L 运行时,我得到这个错误:android.graphics.drawable.BitmapDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow.

我发现这是一个已知问题,并且可以解决您想将颜色设置为卡片背景的问题,但是有什么解决方案可以让我以编程方式设置背景位图吗?你知道我如何从我的 BitmapDrawable 中创建 RoundRectDrawableWithShadow 吗?

Do you have any idea how could I create RoundRectDrawableWithShadow from my BitmapDrawable?

除非您想重写自己的 CardView 实现,否则不要这样做。

RoundRectDrawableWithShadow 是一个私有包 class,用于获取由 app:cardBackgroundColorsetCardBackgroundColro(int) 提供的 color 并包装它在带有阴影的圆角矩形中以生成可绘制对象。

由于在 API 21 中引入了高程,因此阴影被绘制为 CardView 在先前平台上可绘制的背景的一部分,因此 您无法通过 [= 设置自己的背景15=].

is there any solution with which I could set the bitmap for background programatically?

您可以在卡片中放置 View*Layout 等,并在其上设置一个圆形的可绘制背景。但是,它不会在性能方面有效。

https://developer.android.com/reference/android/support/v4/graphics/drawable/RoundedBitmapDrawable.html

所以是的,如果你绝对需要纯色以外的东西,那就选择 View.setBackground