问题
I want to set dynamically a backgroundColor to a text view in a RecyleView, and thus not all my item will have the same background color for their tag.
This is the pseudo code I'd like to use :
val name = item.type.toLowerCase()
color = ContextCompat(item.context, R.color[name])
But this syntax does not seem to work in Kotlin, and I really have no idea how to fetch the color value from the resource depending on the type of the item.
I also tried this:
val lowerType = pokemon.type.toLowerCase()
val id = holder.context.resources.getIdentifier(lowerType, "id", holder.context.packageName)
val color = ContextCompat.getColor(holder.context, id)
But this crashes too
回答1:
It's not a good idea to access the resources in a dynamic way, you will lose compile-time safety and code completion. In your case, you could create a Map
that associates every view type to the resource you want (i.e. color).
Example
/* colors.xml */
<color name="color_view_1">#AA000000</color>
<color name="color_view_2">#AB000000</color>
<color name="color_view_3">#AC000000</color>
<color name="color_view_4">#AD000000</color>
<color name="color_view_default">#AE000000</color>
/* Adapter */
enum class ViewType {
TYPE1, TYPE2, TYPE3
}
val colors = mapOf(
ViewType.TYPE1 to R.color.color_view_1,
ViewType.TYPE2 to R.color.color_view_2,
ViewType.TYPE3 to R.color.color_view_3
)
/* onBindViewHolder */
val color = colors[viewType] ?: R.color.color_view_default
回答2:
You should set "color"
and not "id"
for getIdentifier()
's 2nd argument:
val id = holder.context.resources.getIdentifier(lowerType, "color", holder.context.packageName)
来源:https://stackoverflow.com/questions/54244998/accessing-dynamically-to-a-kotlin-class-property