残念ながら、既定の書体を変更するだけで、アプリケーションで使用しているすべてのTextViewの書体を変更することはできません。
あなたができることは、独自のカスタムTextViewを作成し、それに#josedlujanの提案するような書体を設定することです。しかし、そのアプローチの欠点は、TextViewオブジェクトが作成されるたびに、新しいTypefaceオブジェクトが作成され、RAM使用に非常に悪いことです(TypefaceオブジェクトはRoboteのような書体の場合、通常8-13kbです)。そのため、読み込まれたTypefaceをキャッシュするほうがよいでしょう。
ステップ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:あなたのCustomTextViewためattrs.xmlで独自のカスタム属性 "customFont" を定義し
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();
}