Cardview Set Background color

10,925

Solution 1

method setCardBackgroundColor takes color parameter which means that color represented as 4 byte integer in ARGB format, but you pass into method R.color.LightCyan which isn't color but index of color inside of application/system resources. To get color you should use Color.argb(int alpha, int red, int green, int blue) or Resources.getColor(int index, Theme theme) or use ContextCompat to use it on older platforms.

Solution 2

AS UPDATE ON MARCH 2016

Android Support Library 23.2.1(latest), a new getColor() method has been added to ContextCompat.

So, use:

ContextCompat.getColor(context, R.color.your_color);

from official doc:

Returns a color associated with a particular resource ID and styled for the current theme.

getColor(Context context, int id) Returns a color associated with a particular resource ID Starting in M, the returned color will be styled for the specified Context's theme.

Please check ContextCompat http://developer.android.com/intl/es/reference/android/support/v4/content/ContextCompat.html

Share:
10,925
Madhukar Hebbar
Author by

Madhukar Hebbar

JAVA/Android developer in telecom domain

Updated on June 13, 2022

Comments

  • Madhukar Hebbar
    Madhukar Hebbar almost 2 years

    I am trying to change the Cardview background color dynamically in the Bindview holder of RecylerView like this.

    holder.cardView.setCardBackgroundColor(R.color.LightCyan);
    

    The strange thing is the background is applying the almost opposite of the applied color.(#E0FFFF-LightCyan) to 1F0000 -Almost Black)

    I had verified few colors here here and the result is same.

    But if I set like this

    holder.cardView.setCardBackgroundColor(ContextCompat.getColor(this.mContext, R.color.LightCyan));
    

    It worked perfectly.(Yes it's the correct way to set).

    CardView XML:

    <android.support.v7.widget.CardView
        android:id="@+id/cv"
        android:foreground="?selectableItemBackground"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    

    OS : Android 6.0 HTC

    But where is the understanding gap here?