In this post, we’ll look at a generalized approach, which is more complex, but also more suitable for a repeated use of custom fonts.
Extending TextView
We’ll create a new Java class, which extends TextView. This allows us to use that class in all XML views. It inherits all functionality and properties of a regular TextView but adds our custom font.
public class CustomTextView extends TextView { public CustomTextView (Context context) { super(context); applyCustomFont(context); } public CustomTextView (Context context, AttributeSet attrs) { super(context, attrs); applyCustomFont(context); } public CustomTextView (Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); applyCustomFont(context); } private void applyCustomFont(Context context) { if (!isInEditMode()) { Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/Ubuntu-Regular.ttf"); setTypeface(tf); } } }
The first three methods are just constructors, which we override to call a single method applyCustomFont(). That method is the important piece of the puzzle. Lastly, we’ve to call setTypeface() with the font and we’re almost done. In case you’re wondering, we can call the setTypeface() directly (and not on a TextView object), since we’re extending the TextView class.
Using the Class
You might wonder, if so much preparation is worth the effort. In this section you’ll see that it is indeed. Because all you’ve left to do is use the class in an XML view and it automatically has your custom font. There is no Java code necessary.
<RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.w2class.uicomponent.CustomTextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textColor="@color/eat_foody_green_dark" android:textSize="20sp" android:text="w2class Blog" android:layout_marginBottom="24dp"/> </RelativeLayout>
As you can see, you can continue to use all niceties (e.g. textSize, textColor) of TextView. Now, just replace all <TextView/> elements with the class we just created, for example <com.w2class.uicomponent.CustomTextVIew/> and you applied your custom font everywhere!