在 strings.xml 中更改 TextView 的一部分的颜色
Change the color of a part of a TextView in strings.xml
在我使用 Kotlin 的 android 应用程序中,我创建了一个布局,其中有一个显示一些文本的 TextView。对于文本,我在 strings.xml 中有一个项目,我想在其中更改部分文本的颜色,我尝试了以下代码:
<string name="description">the product is <font fgcolor="green"> free </font></string>
但是,颜色没有变。
我只想将“免费”的颜色更改为绿色,谁能解释一下我该怎么做?
改用<font color="#008000">free</font>
。根据the documentation,正确的属性名称是color
,它只支持十六进制代码。
Ben P. 的精彩回答应该可以满足您的用例。但是,我想向您介绍另一种实现此目的的方法。
您可以使用SpannableString来达到同样的效果。使用 SpannableString,您可以为字符串的任何部分设置多种行为(颜色、font-weight、font-size、click-behaviour 等)。
对于你问题中的字符串,你可以这样做:
// 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);
在我使用 Kotlin 的 android 应用程序中,我创建了一个布局,其中有一个显示一些文本的 TextView。对于文本,我在 strings.xml 中有一个项目,我想在其中更改部分文本的颜色,我尝试了以下代码:
<string name="description">the product is <font fgcolor="green"> free </font></string>
但是,颜色没有变。 我只想将“免费”的颜色更改为绿色,谁能解释一下我该怎么做?
改用<font color="#008000">free</font>
。根据the documentation,正确的属性名称是color
,它只支持十六进制代码。
Ben P. 的精彩回答应该可以满足您的用例。但是,我想向您介绍另一种实现此目的的方法。
您可以使用SpannableString来达到同样的效果。使用 SpannableString,您可以为字符串的任何部分设置多种行为(颜色、font-weight、font-size、click-behaviour 等)。
对于你问题中的字符串,你可以这样做:
// 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);