Skip to content

Instantly share code, notes, and snippets.

@hrules6872
Last active March 30, 2016 09:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrules6872/c19ec1de3bfe0a48a176 to your computer and use it in GitHub Desktop.
Save hrules6872/c19ec1de3bfe0a48a176 to your computer and use it in GitHub Desktop.
TextViewFont (cached)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewFont">
<attr name="typeface" format="string"/>
</declare-styleable>
</resources>
public class TextViewFont extends TextView {
public TextViewFont(Context context) {
this(context, null);
}
public TextViewFont(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TextViewFont(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context, attrs);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public TextViewFont(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(context, attrs);
}
private void init(Context context, AttributeSet attrs) {
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.TextViewFont);
String typeface = typedArray.getString(R.styleable.TextViewFont_typeface);
setTypeface(TextViewFontCache.getFont(context, typeface));
typedArray.recycle();
}
}
public class TextViewFontCache {
private static final Map<String, Typeface> mapFont = new HashMap<>();
public static Typeface getFont(Context context, String fontName) {
Typeface typeface = mapFont.get(fontName);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontName);
} catch (Exception e) {
typeface = Typeface.DEFAULT;
}
mapFont.put(fontName, typeface);
}
return typeface;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment