Можете ли вы установить переменную fontFamily в Android?

Я хотел бы знать, возможно ли установить переменную fontFamily в Android Studio, как это можно сделать со строками.

Я не хочу делать что-то необычное, как пользовательские шрифты. Я просто хочу иметь удобство - возможность менять fontFamily для каждого textView одновременно.

До сих пор я не смог найти тег шрифта. Я надеюсь, что некоторые из вас могут мне помочь.

С уважением и заранее спасибо:)

2 ответа

Создайте пользовательский класс TextView и используйте его в 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();
    }
}
}

Поместите otf-файл шрифта в /assets/fonts, создайте утилиты для работы со шрифтами, например:

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");
        }
    }
}

Инициируйте шрифты, когда onCreate your MainAcitivity

TypefaceUtils.initTypeface(this);

Установите нужный шрифт, например:

textView.setTypeface(TypefaceUtils.getMyFont1());
Другие вопросы по тегам