您不能从 xml 中包含它。你必须通过这样的代码来做到这一点:
final TextView myTextView = getTextView();
final AssetManager assets = ctx.getAssets();
final Typeface font = Typeface.createFromAsset(assets, "thamoa.ttf");
setTypeface(font);
一个绝妙的技巧是扩展 TextView 并在运行时自动应用字体。
public class CustomTextView extends TextView {
public CustomTextView(Context ctx) {
super(ctx);
setupText(ctx);
}
public CustomTextView(Context ctx, AttributeSet attrs) {
super(ctx, attrs);
setupText(ctx);
}
public CustomTextView(Context ctx, AttributeSet attrs, int defStyle) {
super(ctx, attrs, defStyle);
setupText(ctx);
}
private void setupText(Context ctx) {
// check if in edit mode and return. Fonts can't be applied when viewing from editor
if(isInEditMode()) {
return;
}
final AssetManager assets = ctx.getAssets();
final TypeFace font = Typeface.createFromAsset(assets, "thamoa.ttf");
setTypeface(font);
}
}
然后你可以以同样的方式使用它,但在 xml 中像这样引用它:
<package.containing.class.CustomTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<!-- whatever attributes that would normally apply here -->
/>