Holly Ikki
Holly Ikki

Reputation: 199

Android change color part of a string

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));
    }

Upvotes: 3

Views: 5342

Answers (2)

Bob
Bob

Reputation: 13850

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);
}

Upvotes: 8

Murat Karagöz
Murat Karagöz

Reputation: 37624

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));

Upvotes: 2

Related Questions