不幸的是,没有直接的方法可以通过更改默认字体来更改您在应用中使用的所有TextView的字体。
你可以做的是创建自己的自定义TextView并按照#josedlujan所建议的设置字体。但是这种方法的缺陷是每次创建一个TextView对象时,都会创建一个新的Typeface对象,这对RAM的使用来说是非常糟糕的(对于像Roboto这样的字体,字体对象通常会在8-13 kb之间变化)。所以最好在你的字体被加载后缓存。
步骤1:创建为您的应用字样缓存 -
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步:在attrs.xml定义自己的自定义属性 “CustomFont的” 为您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();
}