Skip to content

Instantly share code, notes, and snippets.

@ahmedyehya92
Created March 20, 2019 18:30
Show Gist options
  • Save ahmedyehya92/0c9af95a25513a1d78c06997192f6eae to your computer and use it in GitHub Desktop.
Save ahmedyehya92/0c9af95a25513a1d78c06997192f6eae to your computer and use it in GitHub Desktop.
CustomFontTextView
public class CustomFontTextView extends android.support.v7.widget.AppCompatTextView {
public static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context, attrs);
}
public CustomFontTextView(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.CustomFontTextView);
String fontName = attributeArray.getString(R.styleable.CustomFontTextView_custom_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.font_name_SFUIDisplay_Medium))) {
return FontCache.getTypeface("fonts/SFUIDisplay_Medium.ttf", context);
} else if (fontName.contentEquals(context.getString(R.string.font_name_SFUIDisplay_Light))) {
return FontCache.getTypeface("fonts/SFUIDisplay-Light.ttf", context);
}
else if (fontName.contentEquals(context.getString(R.string.font_name_SFUIDisplay_Bold))) {
return FontCache.getTypeface("fonts/SFUIDisplay-Bold.ttf", context);
}
else if (fontName.contentEquals(context.getString(R.string.font_name_SFUIDisplay_Regular))) {
return FontCache.getTypeface("fonts/SFUIDisplay-Regular.ttf", context);
}
else if (fontName.contentEquals(context.getString(R.string.font_name_ScriptMTBold)))
{
return FontCache.getTypeface("fonts/ScriptMTBold.ttf", context);
}
else if(fontName.contentEquals(context.getString(R.string.font_name_Segoe_UI))) {
return FontCache.getTypeface("fonts/Segoe_UI.ttf", context);
}
else if (fontName.contentEquals(context.getString(R.string.font_name_Segoe_UI_Semibold))){
return FontCache.getTypeface("fonts/Segoe_UI_Semibold.ttf", context);
}
else {
// no matching font found
// return null so Android just uses the standard font (Roboto)
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment