Android 在strings.xml中更改TextView部分的颜色
在我使用Kotlin的android应用程序中,我创建了一个布局,其中有一个文本视图显示一些文本。对于strings.xml中的文本,我想更改部分文本的颜色,我尝试了以下代码:Android 在strings.xml中更改TextView部分的颜色,android,string,textview,Android,String,Textview,在我使用Kotlin的android应用程序中,我创建了一个布局,其中有一个文本视图显示一些文本。对于strings.xml中的文本,我想更改部分文本的颜色,我尝试了以下代码: <string name="description">the product is <font fgcolor="green"> free </font></string> 该产品是免费的 但是,颜色没有改变。 我只想把“免费”的
<string name="description">the product is <font fgcolor="green"> free </font></string>
该产品是免费的
但是,颜色没有改变。
我只想把“免费”的颜色改成绿色,有人能解释一下我是怎么做到的吗?用free
代替。根据,正确的属性名称是color
,它只支持十六进制代码。请改用free
。根据,正确的属性名称是color
,它只支持十六进制代码。的精彩答案应该满足您的用例。然而,我想向你们展示实现这一目标的另一种方法
您可以使用来实现相同的效果。使用SpannableString,可以为字符串的任何部分设置多种行为(颜色、字体大小、字体大小、单击行为等)
对于问题中的字符串,可以执行以下操作:
// 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);
的精彩答案应该满足您的用例。然而,我想向你们展示实现这一目标的另一种方法
您可以使用来实现相同的效果。使用SpannableString,可以为字符串的任何部分设置多种行为(颜色、字体大小、字体大小、单击行为等)
对于问题中的字符串,可以执行以下操作:
// 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);