highlight Keyword by regular expression - Android android.text

Android examples for android.text:SpannableString

Description

highlight Keyword by regular expression

Demo Code

import android.app.Activity;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageManager;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ForegroundColorSpan;
import android.text.style.URLSpan;
import android.text.style.UnderlineSpan;
import android.widget.TextView;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main{

    public static SpannableString highlightKeyword(String str, String key,
            int highlightColor) {
        if (!str.contains(key)) {
            return null;
        }/*from  ww w  . j a  v  a 2s .  co  m*/
        SpannableString sp = new SpannableString(str);
        key = Pattern.quote(key);
        Pattern p = Pattern.compile(key);
        Matcher m = p.matcher(str);

        while (m.find()) { 
            int start = m.start();
            int end = m.end();
            sp.setSpan(new ForegroundColorSpan(highlightColor), start, end,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return sp;
    }

}

Related Tutorials