android - 如何在 RecyclerView 中使用 getColor?

标签 android

我正在尝试使用 RecycleView Adapter 中资源的颜色

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

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

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

我可以通过制作局部变量来获得颜色:

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

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

最佳答案

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

关于android - 如何在 RecyclerView 中使用 getColor?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70041582/

相关文章:

android - mp.pause();使应用程序崩溃

android - ListView 不显示。使用 SherlockFragment 和 SimpleCursorAdapter

java - addProximityAlert 和 KEY_PROXIMITY_ENTERING

android - 类和回收器 View 错误 : can't instantiate class

android - 如何在抽屉导航菜单中名为 "view downloads"的选项之一中显示下载的图像(历史记录)

android - 在 Android/多线程上实现 JmDNS

android - 如何使用 ORMan orm 执行以下 SQL 查询?

android - GestureListener 不适用于 android :autoLink ="email"

java - 如何从 Throwable ex 获取整个回溯

java - 没有在 Selenium + Appium 上获取动态 ListView 的所有元素