如何添加可在整个应用程序中使用的字体?

时间:2013-10-11 06:25:29

标签: android android-fonts

感谢this post,我知道您可以在活动中添加字体,并可以在该类中使用它。使用:

 TextView hindiTextView=(TextView)findViewById(R.id.txtbx);
 Typeface hindiFont=Typeface.createFromAsset(getAssets(),"fonts/fontname.ttf");
 mytextView.setTypeface(hindiFont);

但是,如果我想在一个地方添加字体并在整个应用程序中使用它,该怎么办? (如清单或某些属性文件)

3 个答案:

答案 0 :(得分:1)

实际上,没有办法为整个应用程序实现常用的自定义字体。  结帐HERE 也就是说:不,您无法为整个应用设置字体。

但是如果您想尝试一下,请尝试以下引用HERE

常用字体类:

public final class FontsOverride {

    public static void setDefaultFont(Context context,
            String staticTypefaceFieldName, String fontAssetName) {
        final Typeface regular = Typeface.createFromAsset(context.getAssets(),
                fontAssetName);
        replaceFont(staticTypefaceFieldName, regular);
    }

    protected static void replaceFont(String staticTypefaceFieldName,
            final Typeface newTypeface) {
        try {
            final Field StaticField = Typeface.class
                    .getDeclaredField(staticTypefaceFieldName);
            StaticField.setAccessible(true);
            StaticField.set(null, newTypeface);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

然后您需要重载几个默认字体,例如:

FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset3.ttf");

当然,如果你使用相同的字体文件,你可以改进它只加载一次。

答案 1 :(得分:0)

不,抱歉。您只能使用刚编写的代码添加自定义字体。

答案 2 :(得分:0)

创建一个扩展TextView的自定义类,添加它们的字体逻辑。不要在布局中使用Android TextView,而是使用<com.mypackage.myTextView android:id="@+id/myid />

相关问题