2016-04-04 273 views
3

我想在这样的RecylerView的Bindview持有者中动态地更改Cardview背景颜色。Cardview设置背景颜色

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

奇怪的是后台应用几乎相反的应用的颜色。(#E0FFFF-浅青绿),以1F0000 -Almost黑色)

我曾在这里验证几种颜色here,其结果是相同。

但如果我这样设置

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

它完美地工作。(是的,它是设置正确的方式)。

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

但是,在这里认识差距?

+1

[这是你的差距(http://developer.android.com/intl/es/reference/android/support/v4/content/ContextCompat.html) – Aks4125

回答

4

方法setCardBackgroundColor采用颜色参数,即ARGB格式表示为4字节整数的颜色,但是您将传入方法R.color.LightCyan,该方法不是颜色,而是应用程序/系统资源中的颜色索引。要获得颜色,您应该使用Color.argb(int alpha, int red, int green, int blue)Resources.getColor(int index, Theme theme)或使用ContextCompat在较旧的平台上使用它。

+0

明白了。谢谢(你的)信息。 –

+0

我使用硬编码的颜色进行测试,但我不知道alpha因素是强制性的。我将'card.setCardBackgroundColor(0xFF0000)'改成了'card.setCardBackgroundColor(0xFFFF0000)',它工作。谢谢(你的)信息。 – Sunshinator

2

为在更新对2016年3月

Android的支持库23.2.1(最新的),一个新的getColor()方法已被添加到ContextCompat。

所以,使用:

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

从官方文档:

返回与特定资源ID相关联和风格为当前主题的颜色。

的getColor(上下文的背景下,INT ID)返回与 特定资源ID以M开始相关的颜色,返回的颜色将 风格为指定的上下文的主题。

请检查ContextCompat http://developer.android.com/intl/es/reference/android/support/v4/content/ContextCompat.html

+0

是的。我正在使用它。为了好奇,我正在用其他方法测试。谢谢。 –