Search code examples
androidtextviewandroid-fontsandroid-typeface

Change Typefaces at runtime for Textview


I have a Custom TextView and i get all my Text from my Server, so i never know what style is coming. For Example this can include bold, italic and more Textstyles. But im not really sure how to handle that during runtime.

I created an assets Folder with all my Fonts i would like to use:

enter image description here

And in my CustomTextView i tried something like this:

public class CustomTextView extends TextView {

private static final String ANDROID_SCHEMA = "http://schemas.android.com/apk/res/android";

public CustomTextView(Context context) {
    super(context);

    applyCustomFont(context, null);
}

public CustomTextView(Context context, AttributeSet attrs) {
    super(context, attrs);

    applyCustomFont(context, attrs);
}

public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    applyCustomFont(context, attrs);
}

private void applyCustomFont(Context context, AttributeSet attrs) {

    //Workaround for Preview Mode
    if (!isInEditMode()) {
        int textStyle = attrs.getAttributeIntValue(ANDROID_SCHEMA, "textStyle", Typeface.NORMAL);

        Typeface customFont = selectTypeface(context, textStyle);
        setTypeface(customFont);

    } else {

        this.setTypeface(null, Typeface.NORMAL);
    }
}

private Typeface selectTypeface(Context context, int textStyle) {

    switch (textStyle) {
        case Typeface.BOLD: // bold
            return FontCache.getTypeface("fonts/OpenSans-Bold.ttf", context);

        case Typeface.ITALIC: // italic
            return FontCache.getTypeface("fonts/OpenSans-Italic.ttf", context);

        default:
            return FontCache.getTypeface("fonts/OpenSans-Regular.ttf", context);
    }
}

}

This is my FontCache Class:

public class FontCache {

//This caches the fonts while minimizing the number of accesses to the assets

private static final HashMap<String, Typeface> fontCache = new HashMap<>();

public static Typeface getTypeface(String fontname, Context context)
{
    Typeface typeface = fontCache.get(fontname);

    if (typeface == null)
    {
        try {
            typeface = Typeface.createFromAsset(context.getAssets(), fontname);

        } catch (Exception e) {
            return null;
        }

        fontCache.put(fontname, typeface);
    }

    return typeface;
}

 }

But thats not how it works, any Ideas how to accomplish this? Thank you!


Solution

  • you could override setTypeface(Typeface tf, int style)

    @Override
    public void setTypeface(Typeface tf, int style) {
        Typeface customFont = selectTypeface(context, textStyle)
        super.setTypeface(customFont, style);
    }
    

    and from the outside you can call it like

     mTextView.setTypeface(null, Typeface.BOLD);