It is written in documentation that the BackgroundColor of CardView can be set in XML with card_view:cardBackgroundColor
. However, I cannot find a corresponding method to change the background dynamically.
Using mCardView.setBackgroundColor(Color.argb(75, 102,80,67));
will cause the CardView to lose the rounded corner and shadow.
if you want to Change CardView Background Color or Card Color programmatically follow below code : CardView cardView = findviewbyid (R.id.cardView_ID) cardView.setCardBackgroundColor (Color.RED); In XML. ...
Thus, a card caption is not an exception. It is drawn by using its skin element image. That is why setting the background color by using the appearance settings is not in effect. To colorize the card caption, I suggest that you handle the CardView.CustomDrawCardCaption event.
These solutions don't work because the card has a cardCornerRadius. if you want to Change CardView Background Color or Card Color programmatically follow below code :
Note: Read below steps very carefully to add CardView library inside your current project. 1. Open your project’s build.gradle ( Module : app ) file. 2. Please add below code inside your build.gradle ( Module : app ) file.
Providing background color to the child class of cardview will leave the padded parts in case if the card view has any, without color and this is not a good approach.
Dynamically change the card view color as below, assuming you have a adapter to load the list in the card view.
In constructor of adapters Viewholder class
mCardView = (CardView) itemView.findViewById(R.id.card_view);
In onBindViewHolder method of the adapter class :
holder.mCardView.setCardBackgroundColor(Color.GREEN); // will change the background color of the card view to green
Where holder is the object of your viewholder class.
I got it to work nicely by setting the background of the CardView's child:
<android.support.v7.widget.CardView
android:id="@+id/card_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:orientation="vertical"
android:id="@+id/card_layout"
android:layout_width="match_parent"
android:layout_height="72dp"/>
</android.support.v7.widget.CardView>
Then
View cardLayout = mCardView.findViewById(R.id.card_layout);
cardLayout.setBackgroundColor(Color.GREEN);
Using only the Color.GREEN you will not have the result you expect.
Use ContextCompat.getColor(@NonNull context: Context, @ColorRes id: Int)
It returns a color associated with a particular resource ID
View cardLayout = mCardView.findViewById(R.id.card_layout);
cardLayout.setBackgroundColor(ContextCompat.getColor(this, Color.GREEN));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With