Accessing Dynamically To A Kotlin Class Property
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
Solution 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>
<colorname="color_view_2">#AB000000</color><colorname="color_view_3">#AC000000</color><colorname="color_view_4">#AD000000</color><colorname="color_view_default">#AE000000</color>/* Adapter */enumclassViewType {
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
Post a Comment for "Accessing Dynamically To A Kotlin Class Property"