I have a MaterialCardView for a RecyclerView, each element has its importance and the outline of each element should be the corresponding colour.
Here is my XML:
<com.google.android.material.card.MaterialCardView
app:strokeColor="@color/low_importance_green"
app:strokeWidth="@dimen/cardview_border_width"
app:rippleColor="@color/low_importance_green">
And here the code where the colour should be set:
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val colour = when (viewModel.importance){
1 -> R.color.high_importance_red
2 -> R.color.medium_importance_yellow
else -> R.color.low_importance_green
}
holder.card.setRippleColorResource(colour)
holder.card.strokeColor = colour
}
Simply applying the strokeColor in xml (and not changing colour) works fine:
But using the onBindViewHolder() to change the strokeColor, I get this:
IMAGE: setting via code individually fails
And just to be sure, the ripple colour that is set for the cardview works fine and has no issues.
What could lead to this behaviour?
I have one guess, which might be something about the MaterialTheme being applied because the grey has some very slight purple to it. But why should it and how do i fix that?
The problem is in how you use the API.
If you take a look at the source code of MaterialCardView#setStrokeColor you will see that the method requires @ColorInt
. @ColorInt
means that the variable represents a packed color int, AARRGGBB
.
However, in your code you are referring to a resource address (aka @ColorRes
). This is a color resource reference (e.g. android.R.color.black
).
val colour = when (viewModel.importance){
1 -> R.color.high_importance_red
2 -> R.color.medium_importance_yellow
else -> R.color.low_importance_green
}
As long as both the resource (@ColorRes
) and the actual color value (@ColorInt
) are both integers
the method is working but doing a completely different thing from what you expected to see.
To convert your reference
to color
you need to extract it from the resources using Resources#getColor
method.
Luckily, there is a compat
version ContextCompat#getColor
To fix the problem you need to change
holder.card.strokeColor = colour
with
holder.card.strokeColor = ContextCompat.getColor(holder.card.context, colour)