Skip to content

Instantly share code, notes, and snippets.

@gtomek
Created February 15, 2016 14:14
Show Gist options
  • Save gtomek/32a280705e0e5d768d2f to your computer and use it in GitHub Desktop.
Save gtomek/32a280705e0e5d768d2f to your computer and use it in GitHub Desktop.
Andorid fonts face utils
/**
* Utility class for fonts manipulations.
*/
public final class FontFaceUtils {
public static final LruCache<String, Typeface> sCache = new LruCache<>(6);
private FontFaceUtils() {
}
public static void setFont(TextView view, String fontName) {
if (fontName == null) {
Timber.w(new IllegalArgumentException(), "No fontFace is found in textAppearance or you haven't overridden it with the @string/systems_roboto");
return;
}
AssetManager assetManager = view.getContext().getAssets();
Typeface typeface = getFontFace(assetManager, fontName);
if (typeface == null) return;
view.setTypeface(typeface);
}
public static Typeface getFontFace(AssetManager assetManager, String fontName) {
Typeface typeface = sCache.get(fontName);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(assetManager, "fonts/" + fontName);
sCache.put(fontName, typeface);
} catch (RuntimeException e) {
Timber.w(e, "FontName does not correspond to a font in assets");
}
}
return typeface;
}
/**
* Read Style Attributes and ApplyFont
*
* @param view
* @param attrs
* @param defStyleAttr
* @param defStyleRes
*/
public static void readStyleAttributesAndApplyFont(TextView view, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
if (attrs == null) return;
final Resources.Theme theme = view.getContext().getTheme();
final String systemsRoboto = view.getContext().getString(R.string.systems_roboto);
TypedArray viewTypedArray = null;
TypedArray textAppearanceStyleTypedArray = null;
try {
viewTypedArray = theme
.obtainStyledAttributes(attrs, new int[]{android.R.attr.textAppearance}, defStyleAttr, defStyleRes);
int textAppearanceStyle = viewTypedArray.getResourceId(0, -1);
if (textAppearanceStyle != -1) {
textAppearanceStyleTypedArray = theme.obtainStyledAttributes(textAppearanceStyle, R.styleable.View);
String fontFaceName = textAppearanceStyleTypedArray.getString(R.styleable.View_fontFace);
if (!systemsRoboto.equals(fontFaceName))
setFont(view, fontFaceName);
}
} finally {
if (viewTypedArray != null) {
viewTypedArray.recycle();
}
if (textAppearanceStyleTypedArray != null) {
textAppearanceStyleTypedArray.recycle();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment