set Texts Color And Size for TextView - Android android.widget

Android examples for android.widget:TextView

Description

set Texts Color And Size for TextView

Demo Code

import android.content.Context;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.widget.TextView;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

public class Main{

    public static void setTextsColorAndSize(TextView textView, String text,
            int color, String reg_start, String reg_end, float size) {
        if (isNull(text))
            return;
        SpannableStringBuilder styledText = new SpannableStringBuilder();
        List<Location> locations = new ArrayList<>();

        String[] contents = text.trim().split(reg_end);
        if (contents.length == 0)
            return;
        for (String ss : contents) {
            int startIndex = ss.indexOf(reg_start);
            if (startIndex != -1) {
                Location location = new Location();
                location.start = styledText.length() + startIndex;
                location.end = styledText.length() + ss.length() - 1
                        - reg_start.length();
                locations.add(location);
                ss = ss.replace(reg_start, "");
                styledText.append(ss);/* w w  w .j  a  va2 s  . c  o  m*/
            } else if (!ss.contains(reg_start) && !ss.contains(reg_end)) {
                styledText.append(ss);
            }
        }
        for (Location location : locations) {
            styledText.setSpan(new ForegroundColorSpan(color),
                    location.start, location.end + 1,
                    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (size > 0) {
                styledText.setSpan(new RelativeSizeSpan(size),
                        location.start, location.end + 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }

        }
        textView.setText(styledText);
    }

}

Related Tutorials