我在我的应用程序中使用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>

当前回答

试试这个库,它轻量级且易于实现

https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />

其他回答

仅仅设置应用程序的字体为普通,sans, serif或monospace(不是自定义字体!),你可以这样做。

定义一个主题,并将android:typeface属性设置为你想在styles.xml中使用的字体:

<resources>

    <!-- custom normal activity theme -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <!-- other elements -->
        <item name="android:typeface">monospace</item>
    </style>

</resources>

在AndroidManifest.xml文件中将主题应用到整个应用:

<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
    <application
        android:theme="@style/AppTheme" >
    </application>
</manifest>

android参考

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

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

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

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

complie'me.anwarshahriar:calligrapher:1.0'

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

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

这是最优雅快捷的方法。

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

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

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

试试这个库,它轻量级且易于实现

https://github.com/sunnag7/FontStyler

<com.sunnag.fontstyler.FontStylerView
              android:textStyle="bold"
              android:text="@string/about_us"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:paddingTop="8dp"
              app:fontName="Lato-Bold"
              android:textSize="18sp"
              android:id="@+id/textView64" />