Use this custom font class
public class TextView extends android.widget.TextView {
Context mContext;
String str;
//fonts
public static Typeface Font_name;
public TextView(Context context) {
super(context);
mContext=context;
initialiseFont(null);
}
public TextView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext=context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0);
try {
str = ta.getString(R.styleable.TextView_font_family);
} finally {
ta.recycle();
}
initialiseFont(str);
}
public TextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mContext=context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0);
try {
str = ta.getString(R.styleable.TextView_font_family);
} finally {
ta.recycle();
}
initialiseFont(str);
}
public TextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
mContext=context;
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.TextView, 0, 0);
try {
str = ta.getString(R.styleable.TextView_font_family);
} finally {
ta.recycle();
}
initialiseFont(str);
}
private void initialiseFont(String font) {
if(font==null || font.equals("")){
}
else {
Font_name = Typeface.createFromAsset(mContext.getAssets(), font);
setTypeface(Font_name);
}
}
}
Add this tag in arrs.xml to read custom attribute font-family
<resources>
<declare-styleable name="TextView">
<attr name="font_family" format="string"/>
</declare-styleable>
</resources>
Copy your font in assets folder(Use same file name) and Use this tag if you are using TextView anywhere
<Your_package_name_which_you_created_custom_font_class.TextView
android:text="Hello World!"
android:layout_width="wrap_content"
app:font_family="OpenSans-Bold.ttf"
android:layout_height="wrap_content" />