[英]Android change color part of a string
I have a string name "classe". 我有一个字符串名称“ classe”。 It contains many words and phrases in it.
它包含许多单词和短语。 But I want to change color when string contains the word
"idiom"
. 但是当字符串包含单词
"idiom"
时,我想更改颜色。 I did that programmatically, but it changed the color of all string "classe". 我以编程方式完成了此操作,但是它更改了所有字符串“ classe”的颜色。 I just want to change the color of "idiom" (a part of word, not the whole phrase).
我只想更改“成语”的颜色(单词的一部分,而不是整个短语)。 How can I do that programmatically?
如何以编程方式做到这一点?
if (classe.contains("idiom")) {
txtclasse.setTextColor(getResources().getColor(R.color.orange));
}
Use ForegroundColorSpan. 使用ForegroundColorSpan。
if(classe != null && classe.contains(“idiom”))
{
Spannable spannable = new SpannableString(classe);
spannable.setSpan(new ForegroundColorSpan(Color.BLUE), classe.indexOf(“idiom”), classe.indexOf(“idiom”) + “idiom”.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
txtclasse.setText(spannable);
}
You could use HTML to solve it. 您可以使用HTML来解决它。
origString = txtclasse.getText().toString();
origString = origString.replaceAll("idiom","<font color='red'>idiom</font>");
txtclasse.setText(Html.fromHtml(origString));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.