Home > Back-end >  Kotlin getColor in RecyclerView
Kotlin getColor in RecyclerView

Time:11-20

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:

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?

CodePudding user response:

val myColor = ContextCompat.getColor(holder.myTextView.context, R.color.magenta)
holder.myTextView.setBackgroundColor(myColor)
  • Related