Last active
March 30, 2016 09:36
-
-
Save hector6872/c19ec1de3bfe0a48a176 to your computer and use it in GitHub Desktop.
TextViewFont (cached)
This file contains hidden or 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
<?xml version="1.0" encoding="utf-8"?> | |
<resources> | |
<declare-styleable name="TextViewFont"> | |
<attr name="typeface" format="string"/> | |
</declare-styleable> | |
</resources> |
This file contains hidden or 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
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(); | |
} | |
} |
This file contains hidden or 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
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