Cardview 设置背景色
Cardview Set Background color
我正在尝试像这样在 RecylerView 的 Bindview 持有者中动态更改 Cardview 背景颜色。
holder.cardView.setCardBackgroundColor(R.color.LightCyan);
奇怪的是背景应用的颜色几乎与所应用的颜色相反。(#E0FFFF-浅青色) 到 1F0000 -几乎黑色)
我在这里验证了几种颜色here,结果是一样的。
但是如果我这样设置
holder.cardView.setCardBackgroundColor(ContextCompat.getColor(this.mContext, R.color.LightCyan));
效果很好。(是的,这是正确的设置方式)。
卡片视图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
但是这里的理解差距在哪里?
方法 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) 或使用 ContextCompat 在旧平台上使用它。
2016 年 3 月更新
Android 支持库 23.2.1(最新),ContextCompat 中添加了一个新的 getColor() 方法。
所以,使用:
ContextCompat.getColor(context, R.color.your_color);
来自官方文档:
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.
请检查 ContextCompat http://developer.android.com/intl/es/reference/android/support/v4/content/ContextCompat.html
我正在尝试像这样在 RecylerView 的 Bindview 持有者中动态更改 Cardview 背景颜色。
holder.cardView.setCardBackgroundColor(R.color.LightCyan);
奇怪的是背景应用的颜色几乎与所应用的颜色相反。(#E0FFFF-浅青色) 到 1F0000 -几乎黑色)
我在这里验证了几种颜色here,结果是一样的。
但是如果我这样设置
holder.cardView.setCardBackgroundColor(ContextCompat.getColor(this.mContext, R.color.LightCyan));
效果很好。(是的,这是正确的设置方式)。
卡片视图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
但是这里的理解差距在哪里?
方法 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) 或使用 ContextCompat 在旧平台上使用它。
2016 年 3 月更新
Android 支持库 23.2.1(最新),ContextCompat 中添加了一个新的 getColor() 方法。
所以,使用:
ContextCompat.getColor(context, R.color.your_color);
来自官方文档:
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.
请检查 ContextCompat http://developer.android.com/intl/es/reference/android/support/v4/content/ContextCompat.html