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

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

It didn't work! The whole string phrase were empty on screen :(

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.