EditText突出显示文本

时间:2016-04-24 09:52:29

标签: android android-edittext highlight

我正在制作Android应用程序,必须检查列表中是否有任何单词并突出显示它们。我尝试了以下代码:

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

1 个答案:

答案 0 :(得分:0)

请参阅https://developer.android.com/reference/android/text/SpannableStringBuilder.html

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

另请参阅此主题:SpannableStringBuilder to create String with multiple fonts/text sizes etc Example?

您的代码可能类似于:

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