Created
March 14, 2016 20:18
-
-
Save ekchang/0804e7ddd8de2f68c6eb to your computer and use it in GitHub Desktop.
TypefaceSpannableFactory drop in replacement for Html.fromHtml
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)
duringApplication.onCreate()
. And be sure to replace all of theR.string.__my_font
things with your respective fonts.