apouche
apouche

Reputation: 9973

Accessing Resources IDs using Kotlin & Anko

I am new to Android/Kotlin/Anko and I have a question regarding the way to access color (and probably other) resources from within Anko.

I know that there are helpers like textResource where you simply pass the R.string.my_color to simplify the process of setting resource strings but how about accessing colors using the Resources instance from the View class ?

Let’s say you have a subclass of Button and want to change the text color. If you use the textResource it will change the text string not the color, and if you use textColor then you must specify the real resource ID by using resources.getColor(R.color.my_color, null) which wouldn't be so annoying if you didn't have to pass the optional theme parameter (null here)

Is creating an extension on Resources useful here ?

fun Int.fromResources(resources: Resources): Int {
    return resources.getColor(this, null)
}

What is the recommended way ?

EDIT

I changed the textColor value extension to do just that, which I found the cleanest thing to do except I have no idea if this is really Android friendly

var android.widget.TextView.textColor: Int
    get() = throw AnkoException("'android.widget.TextView.textColor' property does not have a getter")
    set(v) = setTextColor(resources.getColor(v, null))

Upvotes: 3

Views: 3662

Answers (1)

Ribesg
Ribesg

Reputation: 768

I think you can use a property extension like this one instead of the one you suggested:

var TextView.textColorRes: Int
    get() = throw PropertyWithoutGetterException("textColorRes")
    set(@ColorRes v) = setTextColor(resources.getColor(v, null))

Or use ContextCompat as suggested by Damian Petla:

var TextView.textColorRes: Int
    get() = throw PropertyWithoutGetterException("textColorRes")
    set(@ColorRes v) = setTextColor(ContextCompat.getColor(context, v))

You should keep Anko's textColor:

  • Allows you to set a color directly without taking it from XML, if needed at some point
  • Prevents you from importing the wrong textColor (Anko's one or yours), same property names with different behaviour is not a good idea.

Upvotes: 2

Related Questions