如何在Kotlin程序中以编程方式更改文本颜色

5

我在stakeOverFlow上找到了类似的问题,但答案并没有帮助我

文件:values.xml

<color name= "orange_or">#EC7000</color>

在Kotlin中创建我的TextView

private val myText: TextView bi bindView(R.id.my_text)

if (conditionTrue) {
    //my text color = orange_or
}

我该如何在Kotlin中从values.xml文件更改此textView的颜色?
1个回答

15

你可以使用:

   //with a color  
   myText.setTextColor(ContextCompat.getColor(this,R.color.orange_or))
   //with a selector
   myText.setTextColor(AppCompatResources.getColorStateList(this, R.color.xxx))

谢谢您的回答,但我能否从values.xml中获取变量? - ramos jc
@ramossuit 你说的“variable”是什么意思?你可以使用 R.color.orange_or 获取该变量的值。 - Gabriele Mariotti
在项目的values文件中,包含了我们在xml中使用的所有颜色和值。 - ramos jc

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接