0

I'm making android application, that must check if there are any of words in the list and highlight them. I tried following code:

public void checkSyntax() {
//Text variable
data = et.getText().toString();
//Colored text
Spanned text = Html.fromHtml("<font color=\"red\">text</font>");
Spanned smth = Html.fromHtml("<font color=\"green\">its just example</font>");
Spanned owo = Html.fromHtml("<font color=\"blue\">i know html</font>");
//Replace words to colored text in string
data.replace("text", text);
data.replace("smth", smth);
data.replace("owo", owo);
//Set new text
     et.removeTextChangedListener(tw);
     et.setText(data);
     et.addTextChangedListener(tw);
}
1kpunep1
  • 13
  • 2

1 Answers1

0

See https://developer.android.com/reference/android/text/SpannableStringBuilder.html

and

https://developer.android.com/reference/android/text/style/ForegroundColorSpan.html

Also take a look at this thread: SpannableStringBuilder to create String with multiple fonts/text sizes etc Example?

Your code might look something like:

ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);

SpannableStringBuilder b = new SpannableStringBuilder(data);

int redStart = data.indexOf("text");
int redEnd = redStart + "text".length();

if (redStart >= 0) {
    b.setSpan(redSpan, redStart, endEnd, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}

et.setText(b);
Community
  • 1
  • 1