К сожалению, нет прямого способа, с помощью которого можно изменить шрифт всех текстовых элементов, которые вы используете в своем приложении, просто изменив шрифт по умолчанию.
Что вы можете сделать, это создать свой собственный TextView и установить на нем шрифт, как это предлагает #josedlujan. Но недостаток в этом подходе заключается в том, что каждый раз, когда будет создан объект TextView, будет создан новый объект Typeface, который крайне вреден для использования ОЗУ (объект Typeface обычно варьируется от 8-13 kb для шрифтов, таких как Roboto). Поэтому лучше кэшировать свой Typeface после его загрузки.
Шаг 1: Создание кэша Typeface для вашего приложения -
public enum Font {
// path to your font asset
Y("fonts/Roboto-Regular.ttf");
public final String name;
private Typeface typeface;
Font(String s) {
name = s;
}
public Typeface getTypeface(Context context) {
if (typeface != null) return typeface;
try {
return typeface = Typeface.createFromAsset(context.getAssets(), name);
} catch (Exception e) {
return null;
}
}
public static Font fromName(String fontName) {
return Font.valueOf(fontName.toUpperCase());
}
Шаг 2: Определите свой собственный атрибут "customFont" в attrs.xml для CustomTextView
attrs.xml -
<declare-styleable name="CustomFontTextView">
<attr name="customFont"/>
</declare-styleable>
<com.packagename.CustomFontTextView
android:id="@+id/some_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:customFont="rl"/>
Шаг 3: Создайте свой собственный TextView
public class CustomFontTextView extends TextView {
public CustomFontTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
public CustomFontTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public CustomFontTextView(Context context) {
super(context);
init(context, null);
}
private void init(Context context, AttributeSet attrs) {
if (attrs == null) {
return;
}
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomFontTextView, 0 ,0);
String fontName = a.getString(R.styleable.CustomFontTextView_customFont);
String textStyle = attrs.getAttributeValue(styleScheme, styleAttribute);
if (fontName != null) {
Typeface typeface = Font.fromName(fontName).getTypeface(context);
if (textStyle != null) {
int style = Integer.decode(textStyle);
setTypeface(typeface, style);
} else {
setTypeface(typeface);
}
}
a.recycle();
}