set Word Color in TextView - Android User Interface

Android examples for User Interface:TextView

Description

set Word Color in TextView

Demo Code


//package com.java2s;

import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;

import android.text.style.ForegroundColorSpan;

import android.widget.TextView;

public class Main {

    public static void setWordColor(TextView view, int color,
            Object... words) {//w  w w .j  a v  a 2s .com
        CharSequence info = view.getText();
        if (!TextUtils.isEmpty(info) && null != words) {
            SpannableStringBuilder span = new SpannableStringBuilder(info);
            for (int i = 0; i < words.length; i++) {
                if (null != words[i]) {
                    int start = info.toString()
                            .indexOf(words[i].toString());
                    if (-1 != start) {
                        span.setSpan(new ForegroundColorSpan(color), start,
                                start + words[i].toString().length(),
                                Spannable.SPAN_INCLUSIVE_INCLUSIVE);
                    }
                }
            }
            view.setText(span);
        }
    }
}

Related Tutorials