2016-10-07 13:18:28

RecyclerView and problem with color of ImageView’s background

Why we can’t apply background color using resources from R class and we need to use deprecated methods?

Hi.

Today I want to explain a fix for problem I just had. The problem was: In Android app we have a list. I wanted to use recycler view and everything was fine, I could apply texts, dates, values on item’s view holder and everything was fine. Except one thing - I wanted to color cards (recycler items) but couldn’t apply any colors. The problem was common - shared view holder keeps the same color for all cards! To be exact I wanted to apply background color to ImageView object in ViewHolder. Else clause which usually works didn’t help, the same with position getter.

After hours spent on fixes I still wasn’t able to set correct values. But the solution was simple. Applying color by:




imageView.setBackgroundColor(R.id.colorRed);



this don’t work! Even if you can compile your code you won’t see what you expect. The fix is simple, you need to load resources and get color from resources like:



imageView.setBackgroundColor(activity.getResources().getColor(R.id.colorRed));



I know this method is deprecated but this was the only one way to run it without problems with colors! If you know any better solution please let me know in private message. If not this post can be useful :)