Soham Soham - 3 months ago 9
Java Question

Custom font not getting applied

My Custom Font class

public class CustomFontText extends TextView {
/*
* Caches typefaces based on their file path and name, so that they don't have to be created every time when they are referenced.
*/
private static Typeface mTypeface;

public CustomFontText(final Context context) {
super(context, null);
}

public CustomFontText(final Context context, final AttributeSet attrs) {
super(context, attrs, 0);
readAttrs(context, attrs);
}

public CustomFontText(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
readAttrs(context, attrs);
}

private void readAttrs(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomTextView);

// Read the title and set it if any
String fontName = a.getString(R.styleable.CustomTextView_fontname);
if (fontName != null) {
// We have a attribute value
if (mTypeface == null) {
mTypeface = Typeface.createFromAsset(context.getAssets(), fontName);
setTypeface(mTypeface);
}
}

// a.recycle();
}
}


Applying in XMl file

<somepackage.CustomFontText
android:id="@+id/details"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ewfewfewqfewfwef"
custom:fontname="Roboto-Regular.ttf" />


It is not giving any kind of error but I am not able to view any changes in the textview. Changing the fontname makes no difference.

Answer

Moving the code setTypeface(mTypeface); outside the check for mTypeface == null should solve the issue. So the code should look like this:

if (mTypeface == null) {
    mTypeface = Typeface.createFromAsset(context.getAssets(), fontName);
}
setTypeface(mTypeface);

This is because mTypeface is declared static and such all CustomFontText instances share the same typeface (which makes sense for caching). If setTypeface is called inside the check though, it will only get applied once, when the typeface is first loaded.

Comments