简体   繁体   English

更改 strings.xml 中 TextView 一部分的颜色

[英]Change the color of a part of a TextView in strings.xml

In my android app with Kotlin, I created a layout in which there's a TextView that shows some text.在我使用 Kotlin 的 android 应用程序中,我创建了一个布局,其中有一个显示一些文本的 TextView。 For the text I have an item in strings.xml where I want to change the color of part of this Text, I tried the following code :对于我在 strings.xml 中有一个项目的文本,我想更改此文本部分的颜色,我尝试了以下代码:

<string name="description">the product is <font fgcolor="green"> free </font></string>

But, The color didn't change.但是,颜色没有改变。 I just want to change the color of "free" to green, can someone explain how I can achieve this?我只想将“免费”的颜色更改为绿色,有人可以解释我如何实现这一目标吗?

Use <font color="#008000">free</font> instead.请改用<font color="#008000">free</font> According to the documentation , the correct attribute name is color and it only supports hex codes.根据文档,正确的属性名称是color并且它只支持十六进制代码。

Ben P. 's awesome answer should satisfy your use case. Ben P.的精彩答案应该可以满足您的用例。 However, I want to present to you another way you can achieve this.但是,我想向您介绍另一种可以实现这一目标的方法。

You can use SpannableString to achieve the same effect.您可以使用SpannableString来实现相同的效果。 With SpannableString, you can set several behaviours (color, font-weight, font-size, click-behaviour, etc) to any part of your String.使用 SpannableString,您可以为 String 的任何部分设置多种行为(颜色、字体粗细、字体大小、点击行为等)。

For the string in your question, you can do something like this:对于您问题中的字符串,您可以执行以下操作:

// the textview you want to set your coloured text to
TextView textView = (TextView) findViewById(R.id.myTextView);

// declare the string you want to span as a Spannable
Spannable wordtoSpan = new SpannableString("the product is free");  

// set the colour span        
wordtoSpan.setSpan(new ForegroundColorSpan(Color.GREEN), 15, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

// set the text to your TextView
textView.setText(wordtoSpan);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM