我想知道如何检测 SpannableStringBuilder
中的某些指定单词。
我的目的是改变这个词的颜色。
假设我有 SpannableStringBuilder span
,列表中包含我的单词,例如“Name”、“Family”、“Location”等。
在这个阶段我想检查我的 span
是否包含这些词然后改变颜色。
例如我想要这样的东西:
if(span.contain("Name")) // Change Color of the word "Name" every where in this span
if(span.contain("Family")) // Change Color of the word "Family" every where in this span
等等...
有什么方法可以检查吗?任何代码示例将不胜感激。
最佳答案
SpannableStringBuilder
中没有搜索方法,但您可以在将其转换为 String
后使用 indexOf()
:
Set<String> words = new HashSet<String>() {{
add("Name"); add("Family"); add("Location");
}};
String s = span.toString();
for (String word : words) {
int len = word.length();
// Here you might want to add a check for an empty word
for (int i = 0; (i = s.indexOf(word, i)) >= 0; i += len) {
span.setSpan(new ForegroundColorSpan(Color.BLUE), i, i + len, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
关于android - 如何检测 SpannableStringBuilder android 中的特定单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45898794/