Android SpannableString Create getSpanableText(String wholeText, String spanableText)

Here you can find the source of getSpanableText(String wholeText, String spanableText)

Description

get Spanable Text

Declaration

public static SpannableString getSpanableText(String wholeText,
        String spanableText) 

Method Source Code

//package com.java2s;

import android.graphics.Color;

import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.BackgroundColorSpan;

public class Main {

    public static SpannableString getSpanableText(String wholeText,
            String spanableText) {
        if (TextUtils.isEmpty(wholeText))
            wholeText = "";
        SpannableString spannableString = new SpannableString(wholeText);
        if (spanableText.equals(""))
            return spannableString;
        wholeText = wholeText.toLowerCase();
        spanableText = spanableText.toLowerCase();
        int startPos = wholeText.indexOf(spanableText);
        if (startPos == -1) {
            int tmpLength = spanableText.length();
            String tmpResult = "";
            for (int i = 1; i <= tmpLength; i++) {
                tmpResult = spanableText.substring(0, tmpLength - i);
                int tmpPos = wholeText.indexOf(tmpResult);
                if (tmpPos == -1) {
                    tmpResult = spanableText.substring(i, tmpLength);
                    tmpPos = wholeText.indexOf(tmpResult);
                }//  w  w w .  j a  v a  2  s  .  c om
                if (tmpPos != -1)
                    break;
                tmpResult = "";
            }
            if (tmpResult.length() != 0) {
                return getSpanableText(wholeText, tmpResult);
            } else {
                return spannableString;
            }
        }
        int endPos = startPos + spanableText.length();
        do {
            endPos = startPos + spanableText.length();
            spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW),
                    startPos, endPos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            startPos = wholeText.indexOf(spanableText, endPos);
        } while (startPos != -1);
        return spannableString;
    }

    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str))
            return true;

        for (int i = 0; i < str.length(); i++) {
            char c = str.charAt(i);
            if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
                return false;
            }
        }
        return true;
    }
}

Related

  1. makeColoredString(String text, int color)