CardView:设置背景颜色会移除圆边

CardView: Setting background color removes the rounded edges

我有一个带圆角的卡片视图:

 <androidx.cardview.widget.CardView
        android:id="@+id/chronology_card"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="2dp"
        app:cardCornerRadius="12dp">   <------- corner radius set in the layout.

视图显示为圆角。 -> 好的。

通过代码设置背景颜色时...

holder.cardView.setBackgroundColor(getBackgroundColor());

...然后圆角就没有了。它看起来像一个具有正确新颜色的矩形。

如何在运行时设置背景颜色并保持边角?

您可以尝试将此添加到您的 activity 代码中:

CardView cardView = findViewById(R.id.chronology_card);
cardView.setCardBackgroundColor(Color.parseColor("#put here the HEX code for the color"));

我之前试过,转角半径没有任何问题。

CardView 管理自己的圆角可绘制背景。
使用 setBackgroundColor 您将覆盖此背景。

您应该使用方法 setCardBackgroundColor 而不是 setBackgroundColor.