2

I would like to know if it is possible to set a fontFamily variable in Android Studio like you can do with Strings.

I don't want to do anything fancy like custom fonts. I just want to have the convenience of being able to change the fontFamily of every textView at once.

So far I was not able to find a font tag. I hope that some of you can help me.

Best regards and thanks in advance :)

Gustavo Pagani
  • 6,583
  • 5
  • 40
  • 71
Dario
  • 31
  • 5

2 Answers2

1

Make a Custom TextView Class and use it in textview

public class MetaFont extends TextView {


public MetaFont(Context context, AttributeSet attributeSet, int i) {
    super(context, attributeSet, i);
    a(attributeSet);
}

public MetaFont(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    a(attributeSet);
}

public MetaFont(Context context) {
    super(context);
    a(null);
}

private void a(AttributeSet attributeSet) {
    if (attributeSet != null) {
        TypedArray obtainStyledAttributes = getContext().obtainStyledAttributes(attributeSet, ATTRS);
        setTypeface(Typeface.createFromAsset(getContext().getAssets(), "Comfortaa.ttf"));
        obtainStyledAttributes.recycle();
    }
}
}
Gaurav
  • 171
  • 1
  • 13
0

Put the font otf file to /assets/fonts, create a utils for dealing with fonts like:

public class TypefaceUtils {
    private static Typeface myFont1;
    private static Typeface myFont2;

    public static Typeface getMyFont1() {
        return myFont1;
    }

    public static Typeface getMyFont2() {
        return myFont2;
    }

    public static void initTypeface(Context context) {
        if (context != null) {
            myFont1 = Typeface.createFromAsset(context.getAssets(), "fonts/myfont1.otf");
            myFont2 = Typeface.createFromAsset(context.getAssets(), "fonts/myfont2.otf");
        }
    }
}

Init fonts when onCreate your MainAcitivity

TypefaceUtils.initTypeface(this);

Set the font where you need, like:

textView.setTypeface(TypefaceUtils.getMyFont1());
TylerQITX
  • 318
  • 2
  • 9