在style属性中使用自定义字体

时间:2014-09-10 09:15:13

标签: android fonts xamarin

我想要实现的是将style属性添加到我的axml文件中,并使用从Asset加载的自定义字体。

我知道我可以加载这样的内置字体(style.xml):

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
    <item name="android:typeface">monospace</item>
  </style>
</resources>

并使用它(Main.axml):

<TextView
        style="@style/CodeFont"
        local:MvxBind="Text Hello" />

我知道我也可以创建MyCustomTextView扩展TextView并按SetTypeface方法设置字体,但我想在style属性中使用自定义字体。

类似于:

 <resources>
    <style name="CodeFont" parent="@android:style/TextAppearance.Medium">
      <item name="android:typeface">MyCustomFontLoadedFromAsset</item>
    </style>
 </resources>

是否可能(以及如何做)?

4 个答案:

答案 0 :(得分:9)

没有办法直接开箱即用。有一个名为Calligraphy的图书馆,可以让你这样做。它适用于API 7 +

我也看到过使用反射覆盖serif / sans的技巧,以便您可以在styles.xmlIs it possible to set a custom font for entire of application?中定义这些技巧,但我建议采用第一种方法。

答案 1 :(得分:-1)

public class MyApplication extends Application {

    private Typeface normalFont;
    private Typeface boldFont;

    ...

    /**
     * Fonts
     */
    public void setTypeface(TextView textView) {
        if(textView != null) {
            if(textView.getTypeface() != null && textView.getTypeface().isBold()) {
                textView.setTypeface(getBoldFont());
            } else {
                textView.setTypeface(getNormalFont());
            }
        }
    }

    private Typeface getNormalFont() {
        if(normalFont == null) {
            normalFont = Typeface.createFromAsset(getAssets(),"fonts/my_font.ttf");
        }
        return this.normalFont;
    }

    private Typeface getBoldFont() {
        if(boldFont == null) {
            boldFont = Typeface.createFromAsset(getAssets(),"fonts/my_font_bold.ttf");
        }
        return this.boldFont;
    }
}

答案 2 :(得分:-3)

String fontPath = "PT_Sans-Narrow-Web-Regular.ttf";

holder.desc = (TextView) row.findViewById(R.id.msgdesc);
// Loading Font Face
Typeface tf = Typeface.createFromAsset(
        row.getContext().getAssets(), fontPath);

// Applying font
holder.desc.setTypeface(tf);

答案 3 :(得分:-4)

info1 = (TextView) findViewById(R.id.textView1);
Typeface font = Typeface.createFromAsset(this.getAssets(),
            "fonts/KeepCalm-Medium.ttf");
info1.setTypeface(font);
info1.setTextColor(Color.parseColor("#FFFFFF"));
相关问题