Jevon
Jevon

Reputation: 313

Possible to get color with string in kotlin?

Ive had a look at this question but as of the time i typed this question, there aren't any answers with Kotlin code.

in my colours.xml file how would i access colours like these for example using a string?

<resources>
    <!-- Orange -->
    <color name="orangePrimary">#f6a02d</color>
    <color name="orange1">#e3952a</color>
    <color name="orange2">#da8f28</color>
    <color name="orange3">#d08926</color>
</resources>

The Java version is apparently this

int desiredColour = getResources().getColor(getResources().getIdentifier("my_color", "color", getPackageName())); 

when android studio translates the code i get this

val desiredColour: Int = getResources().getColor(
                                    getResources().getIdentifier(
                                        "my_color",
                                        "color",
                                        getPackageName()
                                    )

However packageName() and getResources() turn out red for some reason which means there is an error

So what would the Kotlin version be?

Upvotes: 0

Views: 1404

Answers (2)

MEGHA RAMOLIYA
MEGHA RAMOLIYA

Reputation: 1927

You can set:

snackBar_View.setBackgroundColor(context.resources.getColor(com.example.app.R.color.colorPrimary))

Instead of:

snackBar_View.setBackgroundColor(context.getResources().getColor(R.color.redish))
 

Upvotes: 0

saiful103a
saiful103a

Reputation: 1129

There is only one possible explanation for this. getPackageName() and getResources() are not present where you are pasting the code.

For example if I paste your code in an activity, everything seems good.

val desiredColour = resources.getColor(resources.getIdentifier("my_color", "color", packageName))

with theme:

val desiredColour = resources.getColor(resources.getIdentifier("my_color", "color", packageName),theme)

But if I paste it inside fragment, I need to reference the activity of that fragment to get the package name.

val desiredColour = resources.getColor(resources.getIdentifier("my_color", "color", activity?.packageName))

with theme:

val desiredColour = resources.getColor(resources.getIdentifier("my_color", "color", activity?.packageName),activity?.theme)

And if for some reason you are pasting it elsewhere besides activity or fragment, you need to pass context or activity to call those method.

object TestSingleObject {
    fun getDesiredColour(context: Context) =
        context.resources.getColor(context.resources.getIdentifier("my_color", "color", context.packageName))
}

with theme:

object TestSingleObject {
    fun getDesiredColour(context: Context) =
        context.resources.getColor(context.resources.getIdentifier("my_color", "color", context.packageName), context.theme)
}

Upvotes: 1

Related Questions