3

我想知道如何在SpannableStringBuilder. 我的目的是改变这个词的颜色。

假设我有 SpannableStringBuilder span,列表包括我的单词,如“姓名”、“家庭”、“位置”等。

在这个阶段我想检查我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

所以 ...

有什么方法可以检查吗?任何代码示例将不胜感激。

4

2 回答 2

2

中没有搜索方法,SpannableStringBuilder但您可以indexOf()在将其转换为 a 后使用String

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);
  }
 }
于 2017-08-26T22:11:52.177 回答
1

This is how making multiple color and word :

    SpannableStringBuilder builder = new SpannableStringBuilder(); 
String red = "this is red"; 
SpannableString redSpannable= new SpannableString(red); 
redSpannable.setSpan(new ForegroundColorSpan(Color.RED), 0, red.length(), 0); 
builder.append(redSpannable); 
String white = "this is white"; 
SpannableString whiteSpannable= new SpannableString(white); 
whiteSpannable.setSpan(new ForegroundColorSpan(Color.WHITE), 0, white.length(), 0); 
builder.append(whiteSpannable); 
String blue = "this is blue"; 
SpannableString blueSpannable = new SpannableString(blue); 
blueSpannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, blue.length(), 0); builder.append(blueSpannable); mTextView.setText(builder, BufferType.SPANNABLE);

For finding word indexes do as follow :

int first = str.indexOf("hi"); 
int next = str.indexOf("hi", first+1);

read api

Do this to get all indexes and color them

于 2017-08-26T21:51:43.503 回答