How to apply custom font on TextView Android

Some times we need to apply custom font on a TextView in our application. We can do this by setting typeface to out TextView as below.

TextView textView = (TextView) findViewById(R.id.textView);
//Create a folder named fonts in asset folder and copy your .ttf font in it
Typeface  typeface = Typeface.createFromAsset(getContext().getAssets(),"fonts/yourCustomFont.ttf");
//set typeface to textview
textView.setTypeface(typeface);

In case you have more than two TextView in your application(also in different activities/fragments) which uses custom font, Then it would be better to create a custom TextView class and apply typeface to it, because then you do not need to initialize typeface again and again and then set it to each TextView.

Here is how you can create a custom TextView Class for it.

public class CustomFontTextView extends TextView {
public CustomFontTextView(Context context) {
this(context, null);
}
public CustomFontTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setFont();
}
private void setFont(String fontName) {
Typeface typeface = Typeface.createFromAsset(getContext().getAssets(),"fonts/yourCustomFont.ttf");
setTypeface(typeface);
}
}

and here how you can use it in your application.

<com.example.CustomFontTextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

replace com.example with your application’s package name and you have done!

 

(Visited 120 times, 1 visits today)