如何在Android编程中将EditText的特殊词更改为我的可选颜色?
例如:蓝色单词在写入时变为蓝色;或HTML字样变为绿色。怎么做?
最佳答案
使用SpannableStringBuilder
可以更改EditText
或TextView
的部分文本颜色
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);