2016-04-24 176 views
0

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

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

您是否尝试过使用TextWatcher? –

回答

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

当我键入文本时发生崩溃:java.lang.IndexOutOfBoundsException:setSpan(0 ... 4)结束超出长度0 – 1kpunep1

+0

@ 1kpunep1如果您发布代码,我会查看是否可以发现问题。 –