Possible to get color with string in kotlin?

若如初见. 提交于 2021-01-29 06:43:56

问题


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?


回答1:


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)
}


来源:https://stackoverflow.com/questions/65445066/possible-to-get-color-with-string-in-kotlin

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