3

I have a string name "classe". It contains many words and phrases in it. But I want to change color when string contains the word "idiom". I did that programmatically, but it changed the color of all string "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));
    }
Holly Ikki
  • 199
  • 1
  • 10

2 Answers2

8

Use 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);
}
Bob
  • 13,447
  • 7
  • 35
  • 45
2

You could use HTML to solve it.

origString = txtclasse.getText().toString();
origString = origString.replaceAll("idiom","<font color='red'>idiom</font>");

txtclasse.setText(Html.fromHtml(origString));
Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107