How to detect specific Words in SpannableStringBuilder android?

1k views Asked by At

I want to know how can i detect some specified words in SpannableStringBuilder . My purpose is to change color of this words.

Say i have SpannableStringBuilder span and the list included my Words like "Name" , "Family" , "Location" etc.

In this stage i want to check if my spanis including these words then change color of.

For example I want something like :

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

and so ...

Is there any method to check ? any code example will be appreciated.

2

There are 2 answers

3
Gil Vegliach On BEST ANSWER

There is no search method in SpannableStringBuilder but you can use indexOf() after you convert it to 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);
  }
 }
1
Alireza Sharifi On

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