如何在RecyclerView中使用getColor?

Art*_*yum 4 android

我正在尝试使用 RecycleView 适配器中资源的颜色

override fun onBindViewHolder(holder: NavlogViewHolder, position: Int) {
    holder.myTextView.setBackgroundColor(R.color.magenta)
Run Code Online (Sandbox Code Playgroud)

这会给出一个错误:“应该传递解析的颜色而不是资源 id”,并且颜色不是应该的颜色。这也是错误的:

holder.myTextView.setBackgroundColor(getResources.getColor(R.color.magenta))
holder.myTextView.setBackgroundColor(context.resources.getColor(R.color.magenta))
Run Code Online (Sandbox Code Playgroud)

我可以通过创建局部变量来获取颜色,例如:

val color = "#f7f7f7"
holder.myTextView.setBackgroundColor(Color.parseColor(color))
Run Code Online (Sandbox Code Playgroud)

但我想更好地从colors.xml 中获取颜色如何正确执行?

小智 7

val myColor = ContextCompat.getColor(holder.myTextView.context, R.color.magenta)
holder.myTextView.setBackgroundColor(myColor)
Run Code Online (Sandbox Code Playgroud)