Skip to content

Instantly share code, notes, and snippets.

@ekchang
Created March 14, 2016 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ekchang/0804e7ddd8de2f68c6eb to your computer and use it in GitHub Desktop.
Save ekchang/0804e7ddd8de2f68c6eb to your computer and use it in GitHub Desktop.
TypefaceSpannableFactory drop in replacement for Html.fromHtml
import android.app.Application;
import android.content.res.AssetManager;
import android.graphics.Typeface;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.StyleSpan;
import uk.co.chrisjenx.calligraphy.CalligraphyTypefaceSpan;
import uk.co.chrisjenx.calligraphy.TypefaceUtils;
public class TypefaceSpannableFactory {
static CalligraphyTypefaceSpan bold;
static CalligraphyTypefaceSpan regular;
static CalligraphyTypefaceSpan italic;
private static boolean initialized;
private TypefaceSpannableFactory() {
throw new AssertionError("No instances.");
}
public static void loadAssets(Application app) {
AssetManager assetManager = app.getAssets();
bold = new CalligraphyTypefaceSpan(TypefaceUtils.load(
assetManager,
app.getString(R.string.__my_font_bold)
));
regular = new CalligraphyTypefaceSpan(TypefaceUtils.load(
assetManager,
app.getString(R.string.__my_font_regular)
));
italic = new CalligraphyTypefaceSpan(TypefaceUtils.load(
assetManager,
app.getString(R.string.__my_font_italic)
));
initialized = true;
}
public static Spanned fromHtml(String source) {
if (!initialized) {
throw new AssertionError("Not initialized, must call loadAssets()");
}
Spanned spanned = Html.fromHtml(source);
SpannableStringBuilder builder = new SpannableStringBuilder(spanned);
for (StyleSpan styleSpan : spanned.getSpans(0, spanned.length(), StyleSpan.class)) {
int start = spanned.getSpanStart(styleSpan);
int end = spanned.getSpanEnd(styleSpan);
int flags = spanned.getSpanFlags(styleSpan);
CalligraphyTypefaceSpan typefaceSpan;
switch (styleSpan.getStyle()) {
default:
case Typeface.NORMAL:
typefaceSpan = regular;
break;
case Typeface.BOLD:
typefaceSpan = bold;
break;
case Typeface.ITALIC:
typefaceSpan = italic;
break;
}
builder.removeSpan(styleSpan);
builder.setSpan(typefaceSpan, start, end, flags);
}
return builder;
}
}
@ekchang
Copy link
Author

ekchang commented Mar 14, 2016

Drop in replacement for Html.fromHtml(String). Load a specific bold, italic, normal typeface when parsing standard Html style tags.

Leverages Calligraphy library.

Setup:
Call TypefaceSpannableFactory.loadAssets(this) during Application.onCreate(). And be sure to replace all of the R.string.__my_font things with your respective fonts.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment