Accessing dynamically to a Kotlin class property

可紊 提交于 2021-01-29 07:25:54

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!