可能在Kotlin中使用字符串获得颜色? [英] Possible to get color with string in kotlin?
问题描述
我曾经看过这个问题,但是直到我输入这个问题,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.
在我的colours.xml
文件中,如何使用字符串访问类似这些颜色的颜色?
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>
Java版本显然是这个
The Java version is apparently this
int desiredColour = getResources().getColor(getResources().getIdentifier("my_color", "color", getPackageName()));
当android studio翻译我得到的代码时
when android studio translates the code i get this
val desiredColour: Int = getResources().getColor(
getResources().getIdentifier(
"my_color",
"color",
getPackageName()
)
但是packageName()
和getResources()
由于某些原因变成红色,这意味着有错误
However packageName()
and getResources()
turn out red for some reason which means there is an error
那么Kotlin版本是什么?
So what would the Kotlin version be?
推荐答案
对此只有一种可能的解释.在粘贴代码的位置不存在getPackageName()和getResources().
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))
带有主题:
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))
带有主题:
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))
}
带有主题:
object TestSingleObject {
fun getDesiredColour(context: Context) =
context.resources.getColor(context.resources.getIdentifier("my_color", "color", context.packageName), context.theme)
}
这篇关于可能在Kotlin中使用字符串获得颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!