Jakub Wisniewski
Jakub Wisniewski

Reputation: 2249

androidx custom fonts on lower api's

I am using AndroidX in my Kotlin app and I have been trying to add custom fonts. I have folder in res/font with .ttf files and 2 font families (v26 and normal). v26 file contains android: prefixes while the other file has app: prefixes.

I have also added appcompat and legacy-support implementations in gradle but somehow still I can't get the font to display properly on Android 6.0 (works on newer devices). I am setting the font family in AppTheme as:

    <item name="fontFamily">@font/avalon</item>

I have no idea what else I could try. Did anyone had the same problem?

Upvotes: 0

Views: 443

Answers (1)

vanste25
vanste25

Reputation: 1774

I think that you cannot use fontFamily for custom fonts in older APIs.

However, you can create your own TextView (extend default one) and set custom typeface:

public class MyTextView extends TextView {

public MyTextView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    init();
}

public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public MyTextView(Context context) {
    super(context);
    init();
}

private void init() {
    if (!isInEditMode()) {
        Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/custom.ttf");
        setTypeface(tf);
    }
}

}

Or to set typeface like this:

Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/custom.ttf");
myTextView.setTypeface(typeface);

Upvotes: 1

Related Questions