Set different font and color to part of a TextView
You have to use a TypefaceSpan
instead of a Typeface
.
But since you are using a custom typeface you need to extend TypefaceSpan
.
Check out this answer and create CustomTypefaceSpan
class.
Now do the following:
Typeface robotoRegular = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Regular.ttf");
Typeface robotoBold = Typeface.createFromAsset(getAssets(), "fonts/Roboto-Bold.ttf");
TypefaceSpan robotoRegularSpan = new CustomTypefaceSpan("", robotoRegular);
TypefaceSpan robotoBoldSpan = new CustomTypefaceSpan("", robotoBold);
// normal font for 1st 9 chars
sb.setSpan(robotoRegularSpan, 0, 9, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// bold font for rest of the chars
sb.setSpan(robotoBoldSpan, 9, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
// also change color for rest of the chars
sb.setSpan(new ForegroundColorSpan(Color.BLUE), 9, s.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
textView.setText(sb);
For peaple who prefer to make utils classes for this:
public static SpannableStringBuilder makeTextBold (Activity activity, String string, int fromCharIndex, int toCharIndex) {
return makeTextBold(activity, new SpannableStringBuilder(string), fromCharIndex, toCharIndex);
}
public static SpannableStringBuilder makeTextBold (Activity activity, SpannableStringBuilder string, int fromCharIndex, int toCharIndex) {
SpannableStringBuilder sb = new SpannableStringBuilder(string);
Typeface bold = Typeface.createFromAsset(activity.getAssets(), "fonts/NexaBold.ttf");
TypefaceSpan robotoBoldSpan = new CustomTypefaceSpan("", bold);
sb.setSpan(robotoBoldSpan, fromCharIndex, toCharIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return sb;
}
public static SpannableStringBuilder colorText (int resourceId, String string, Activity activity, int fromCharIndex, int toCharIndex) {
return colorText(resourceId, new SpannableStringBuilder(string), activity, fromCharIndex, toCharIndex);
}
public static SpannableStringBuilder colorText (int resourceId, SpannableStringBuilder sb, Activity activity, int fromCharIndex, int toCharIndex) {
sb.setSpan(new ForegroundColorSpan(activity.getResources().getColor(resourceId)), fromCharIndex, toCharIndex, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
return sb;
}