Android examples for android.widget:TextView
Set Text Color for TextView
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 setSpecifiedTextsColor(TextView textView, String text, int color, String reg_start, String reg_end) { 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);/*from w ww. j a v a 2 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); } textView.setText(styledText); } }