9

The situation is that when I modify a Card view background from a program then the corner radius of the Card view reset. But why?
(I don't think I need to provide any other information (code, picture of the result, etc.), because I think it's clear enough to understand. If you need more information then you should write down in a comment.)

Biscuit
  • 4,840
  • 4
  • 26
  • 54
Noel Nemeth
  • 646
  • 11
  • 21

3 Answers3

29

If you try to use CardView with corner radius you will face this problem when you set background color dynamically. Please use yourCardView.setCardBackgroundColor() methord instead of yourCardView.setBackgroundColor() :)

Amir Dora.
  • 2,831
  • 4
  • 40
  • 61
Dulanga
  • 921
  • 11
  • 23
6

I found a solution to the question.
I needed to retrieve the background of the view and set its color, then I assigned the new background to the view.

Drawable backgroundOff = v.getBackground(); //v is a view
backgroundOff.setTint(defaultColor); //defaultColor is an int 
v.setBackground(backgroundOff);

(This answer helped: https://stackoverflow.com/a/18394982/9377499)

Noel Nemeth
  • 646
  • 11
  • 21
  • Works like a charm for instance when you want to change color of every other `CardView` inside a `RecyclerView` and preserve rounded corners. During the process you are only able to access `CardView` elements as `android.view.View` *itemViews*, which have `setBackgroundColor()` method (it fails) but there is no `setCardBackgroundColor()` method available. – Theta Nov 27 '20 at 22:15
1

Same problem and fix the problem this way

At first, create the shape named in Drawable "shape_background_cardview" and this add below code

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">

<solid android:color="@color/gray500" />
<corners android:radius="5dp" />

</shape>

step second, set the shape to the background CardView yourself

yourCardView.setBackgroundResource(R.drawable.shape_background_cardview);

GoodLuck

Mohamad Rezaei
  • 391
  • 4
  • 9