There is a various way to setup the custom font in android. But It's not simple like iOS, we have to do some stuff. In my experience, an efficient way to do it is create a CustomTextView, the code look like:
public class CustomTextView extends TextView {
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs);
}
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomTextView(Context context) {
super(context);
init(null);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.FontTextView);
String fontName = a.getString(R.styleable.FontTextView_fontName);
if (fontName != null) {
Typeface myTypeface = Typeface.createFromAsset(getContext().getAssets(), "opensans/" + fontName);
setTypeface(myTypeface);
}
a.recycle();
}
}
}
And you can avail yourself of using the custom TextView by create a style for it:
<style name="TextContentStyle" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">@color/textColorPrimary</item>
<item name="fontName">OpenSans-Regular.ttf</item>
</style>
And in layout, we use CustomTextView above style:
<com.xx.xx.CustomTextView style="@style/TextContentStyle"
android:layout_width="match_parent"
android:layout_margin="@dimen/margin_medium"
android:gravity="center"
android:text="@string/txt_menu"
android:textColor="#FFF" />
Moreover, because Typeface.createFromAsset() is not free, so we can optimize code by cache the font which is loaded into memory before.
public class FontCache {
private static Map<String, Typeface> fontMap = new HashMap<String, Typeface>();
public static Typeface getFont(Context context, String fontName){
if (fontMap.containsKey(fontName)){
return fontMap.get(fontName);
}
else {
Typeface tf = Typeface.createFromAsset(context.getAssets(), fontName);
fontMap.put(fontName, tf);
return tf;
}
}
}
That's it! I prefer this way because we can use any font type at anywhere that we want, use multiple font type in an app.