Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Kotlin getColor in RecyclerView

I’m trying to use a color from resources in RecycleView Adapter

override fun onBindViewHolder(holder: NavlogViewHolder, position: Int) {
    holder.myTextView.setBackgroundColor(R.color.magenta)

This gives an error: "should pass resolved color instead of resource id" and color is not what should be. This is also wrong:

holder.myTextView.setBackgroundColor(getResources.getColor(R.color.magenta))
holder.myTextView.setBackgroundColor(context.resources.getColor(R.color.magenta))

I can get a color by making local variable like:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

val color = "#f7f7f7"
holder.myTextView.setBackgroundColor(Color.parseColor(color))

but I’d like better to get color from colors.xml How to do it properly?

>Solution :

val myColor = ContextCompat.getColor(holder.myTextView.context, R.color.magenta)
holder.myTextView.setBackgroundColor(myColor)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading