highlight Text with SpannableString - Android Graphics

Android examples for Graphics:Spannable

Description

highlight Text with SpannableString

Demo Code

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.graphics.Color;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.ForegroundColorSpan;
import android.widget.TextView;

public class Main {
  public static void highlightText(TextView textView, String key) {

    SpannableString s = new SpannableString(textView.getText());
    Pattern p = Pattern.compile(key);
    Matcher m = p.matcher(s);/* w  w  w . jav a 2 s. c  o  m*/
    while (m.find()) {
      int start = m.start();
      int end = m.end();
      s.setSpan(new ForegroundColorSpan(Color.rgb(77, 164, 248)), start, end,
          Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }
    textView.setText(s);
  }
}

Related Tutorials