Skip to content

Instantly share code, notes, and snippets.

@JaydipZala
Created November 19, 2016 11:00
Show Gist options
  • Save JaydipZala/ed37366567b188f3bfc893cc17ee4549 to your computer and use it in GitHub Desktop.
Save JaydipZala/ed37366567b188f3bfc893cc17ee4549 to your computer and use it in GitHub Desktop.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="RobotoTextView">
<attr name="font" format="string" />
</declare-styleable>
</resources>
public class RobotoTextView extends TextView {
public static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";
private static HashMap<String, Typeface> fontCache = new HashMap<>();
public RobotoTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context, attrs);
}
public RobotoTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context, attrs);
}
private void applyCustomFont(Context context, AttributeSet attrs) {
TypedArray attributeArray = context.obtainStyledAttributes(
attrs,
R.styleable.RobotoTextView);
String fontName = attributeArray.getString(R.styleable.RobotoTextView_font);
int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);
Typeface customFont = selectTypeface(context, fontName, textStyle);
setTypeface(customFont);
attributeArray.recycle();
}
private Typeface selectTypeface(Context context, String fontName, int textStyle) {
if (fontName.contentEquals(context.getString(R.string.roboto))) {
return getTypeface("fonts/roboto.ttf", context);
} else if (fontName.contentEquals(context.getString(R.string.roboto_condensed))) {
return getTypeface("fonts/robotocondensed.ttf", context);
} else {
// no matching font found
// return null so Android just uses the standard font (Roboto)
return null;
}
}
public static Typeface getTypeface(String fontname, Context context) {
Typeface typeface = fontCache.get(fontname);
if (typeface == null) {
try {
typeface = Typeface.createFromAsset(context.getAssets(), fontname);
} catch (Exception e) {
return null;
}
fontCache.put(fontname, typeface);
}
return typeface;
}
}
<resources>
<string name="roboto">roboto</string>
<string name="roboto_condensed">robotocondensed</string>
</resources>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment