Android如何更改字符串中的部分颜色

3

我有一个字符串变量 "classe"。它包含很多单词和短语。但是当该字符串包含单词 "idiom" 时,我想要改变其颜色。我已经通过编程实现了,但问题是它改变了整个字符串 "classe" 的颜色,而我只想改变 "idiom" 这一部分的颜色,而不是整个短语。请问如何在程序中实现此要求?

    if (classe.contains("idiom")) {

        txtclasse.setTextColor(getResources().getColor(R.color.orange));
    }

使用 ForegroundColorSpan。请参考此处:https://dev59.com/0nA75IYBdhLWcg3wdIz7#3514435 - Bob
请查看此链接 https://dev59.com/DGw05IYBdhLWcg3weBvu#57089362 - Ketan Ramani
https://stackoverflow.com/a/59628947/12478830 - MMG
2个回答

8
使用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);
}

2
你可以使用HTML来解决这个问题。
origString = txtclasse.getText().toString();
origString = origString.replaceAll("idiom","<font color='red'>idiom</font>");

txtclasse.setText(Html.fromHtml(origString));

它没起作用!整个字符串短语在屏幕上都是空的 :( - Holly Ikki

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