私の研究では、xmlファイルに外部フォントを追加する方法はありません。xmlでは3つのデフォルトフォントのみが使用可能です
ただし、このコードを使用してJavaで使用できます。
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/verdana.ttf");
textfield.setTypeface(tf,Typeface.BOLD);
アップデート:
ここで、TextViewを拡張するカスタムクラスを作成し、それをxmlファイルで使用することでこれを行う方法を見つけました。
public class TextViewWithFont extends TextView {
private int defaultDimension = 0;
private int TYPE_BOLD = 1;
private int TYPE_ITALIC = 2;
private int FONT_ARIAL = 1;
private int FONT_OPEN_SANS = 2;
private int fontType;
private int fontName;
public TextViewWithFont(Context context) {
super(context);
init(null, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0);
}
public TextViewWithFont(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyle) {
// Load attributes
final TypedArray a = getContext().obtainStyledAttributes(
attrs, R.styleable.font, defStyle, 0);
fontName = a.getInt(R.styleable.font_name, defaultDimension);
fontType = a.getInt(R.styleable.font_type, defaultDimension);
a.recycle();
MyApplication application = (MyApplication ) getContext().getApplicationContext();
if (fontName == FONT_ARIAL) {
setFontType(application .getArialFont());
} else if (fontName == FONT_OPEN_SANS) {
setFontType(application .getOpenSans());
}
}
private void setFontType(Typeface font) {
if (fontType == TYPE_BOLD) {
setTypeface(font, Typeface.BOLD);
} else if (fontType == TYPE_ITALIC) {
setTypeface(font, Typeface.ITALIC);
} else {
setTypeface(font);
}
}
}
とxmlで
<com.example.customwidgets.TextViewWithFont
font:name="Arial"
font:type="bold"
android:layout_width="wrap_content"
android:text="Hello world "
android:padding="5dp"
android:layout_height="wrap_content"/>
xmlのルートにスキーマを追加することを忘れないでください
xmlns:font="http://schemas.android.com/apk/res-auto"
そして、カスタム属性を保持しているディレクトリattrs.xml
内にファイルを作成します。values
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="font">
<attr name="type">
<enum name="bold" value="1"/>
<enum name="italic" value="2"/>
</attr>
<attr name="name">
<enum name="Arial" value="1"/>
<enum name="OpenSans" value="2"/>
</attr>
</declare-styleable>
</resources>
アップデート:
このカスタムビューをリストビューで使用すると、パフォーマンスの問題が見つかりました。これは、ビューが読み込まれるたびにフォントオブジェクトが作成されるためです。私が見つけた解決策は、アプリケーションクラスでフォントを初期化し、そのフォントオブジェクトを次のように参照することです。
MyApplication application = (MyApplication) getContext().getApplicationContext();
アプリケーションクラスは次のようになります
public class MyApplication extends Application {
private Typeface arialFont, openSans;
public void onCreate() {
super.onCreate();
arialFont = Typeface.createFromAsset(getAssets(), QRUtils.FONT_ARIAL);
openSans = Typeface.createFromAsset(getAssets(), QRUtils.FONT_OPEN_SANS);
}
public Typeface getArialFont() {
return arialFont;
}
public Typeface getOpenSans() {
return openSans;
}
}