如何在Android编程中将EditText的特殊词更改为我的可选颜色?

例如:蓝色单词在写入时变为蓝色;或HTML字样变为绿色。怎么做?

最佳答案

使用SpannableStringBuilder可以更改EditTextTextView的部分文本颜色

String text = "Hello blue word";
String specialWord = "blue";
int specialWordIndex= text.indexOf(specialWord);

SpannableStringBuilder sb = new SpannableStringBuilder(text);
// Span to set text color to blue (or any color)
ForegroundColorSpan fcs = new ForegroundColorSpan(Color.BLUE);
// Set text color from specialWord first index to specialWord last index
sb.setSpan(fcs, specialWordIndex, specialWordIndex+ specialWord.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

yourEditText.setText(sb);

08-06 12:58