我在我的应用程序中使用Roboto light字体。要设置字体,我必须添加android:fontFamily="sans-serif-light"到每个视图。有什么方法来声明Roboto字体作为默认字体家族整个应用程序?我试过这样做,但似乎不管用。

<style name="AppBaseTheme" parent="android:Theme.Light"></style>

<style name="AppTheme" parent="AppBaseTheme">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

当前回答

答案是否定的,你不能。 是否可以为整个应用程序设置自定义字体? 获取更多信息。

有一些变通方法,但没有“在这里写一行代码,我所有的字体都将是这个而不是那个”。

(我有点感谢谷歌和苹果公司)。自定义字体是有一席之地的,但如果让它们在整个应用程序范围内容易被取代,就会创造出一个Comic Sans应用程序的整个世界)

其他回答

不谈性能,对于自定义字体,你可以有一个递归方法循环通过所有的视图和设置字体,如果它是一个TextView:

public class Font {
    public static void setAllTextView(ViewGroup parent) {
        for (int i = parent.getChildCount() - 1; i >= 0; i--) {
            final View child = parent.getChildAt(i);
            if (child instanceof ViewGroup) {
                setAllTextView((ViewGroup) child);
            } else if (child instanceof TextView) {
                ((TextView) child).setTypeface(getFont());
            }
        }
    }

    public static Typeface getFont() {
        return Typeface.createFromAsset(YourApplicationContext.getInstance().getAssets(), "fonts/whateverfont.ttf");
    }
}

在你的所有活动中,在setContentView之后将当前ViewGroup传递给它,就完成了:

ViewGroup group = (ViewGroup) getWindow().getDecorView().findViewById(android.R.id.content);
Font.setAllTextView(group);

对于片段,也可以做类似的事情。

要改变你的应用字体遵循以下步骤:

在res目录中创建一个新目录并命名为font。 插入字体.ttf/。在字体文件夹otf,确保字体名称是小写字母和下划线。 Inside res -> values -> styles.xml Inside <resources> -> <style>添加你的字体<item name="android:fontFamily">@font/font_name</item>。

现在你所有的应用文本都应该是你添加的字体。

这在Android Studio中非常非常简单。

在这个方法中,你需要验证你的minsdkverison。minsdkversion >=16

在“res”文件夹中创建“font”文件夹。在android studio中新建>文件夹>字体文件夹。

将您的字体文件上传到该字体文件夹。

在你的style.xml文件中,在“Base application theme”的style下添加这一行。 <项目名称= " android: fontFamily " > @font / ubuntubold > < /项目

更多的细节: https://coderog.com/community/threads/how-to-set-default-font-family-for-entire-android-app.72/

Android并没有在整个应用程序中应用字体的方式上提供很多支持(参见本期)。你有4个选项来设置整个应用程序的字体:

选项1:应用反射来更改系统字体 选项2:为每个需要自定义字体的视图创建并子类化自定义视图类 Option3:实现一个遍历视图的视图爬虫 当前屏幕的层次结构 选项4:使用第三方库。

这些选项的详细信息可以在这里找到。

只需使用这个库编译在你的成绩文件

complie'me.anwarshahriar:calligrapher:1.0'

并在主活动的onCreate方法中使用它

Calligrapher calligrapher = new Calligrapher(this);
calligrapher.setFont(this, "yourCustomFontHere.ttf", true);

这是最优雅快捷的方法。