【问题标题】:How to set custom font for a whole application in Android?如何在 Android 中为整个应用程序设置自定义字体?
【发布时间】:2016-02-28 16:10:03
【问题描述】:

是否可以在 Android 应用程序中设置自定义字体?

我尝试了here 发布的内容,但我不知道我的extends Application 课程在哪里...

有什么帮助吗?

编辑:

我尝试了以下方法:

  • 添加资产文件夹并在其中插入字体,如下所示:

  • 添加一个从Application扩展的新类

  • 通过我的AndroidManifest.xml 呼叫这个新课程。

  • 我去了我的风格并添加了它。

MyApp.java:

public class MyApp extends Application {
  @Override
  public void onCreate() {
     super.onCreate();
    FontsOverride.setDefaultFont(this, "DEFAULT", "raleway_regular.ttf");
    //  This FontsOverride comes from the example I posted above
  }
  }

AndroidManifest.xml:

<application
      android:allowBackup="true"
      android:icon="@mipmap/ic_launcher"
      android:label="@string/app_name"
      android:supportsRtl="true"
      android:name=".MyApp"
      android:theme="@style/AppTheme">
     ....

styles.xml:

 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:fontFamily">default</item>
 </style>

但我的字体仍然没有改变...有什么想法吗?

然后调用MyApp 类。但对我的字体没有影响...

EDIT2:我意识到在我为按钮设置自定义样式后,我的按钮会应用自定义字体。这是我的自定义按钮样式:

<style name="MyButtonStyle" parent="Widget.AppCompat.Button">
    <item name="textAllCaps">false</item>
    <item name="android:textAllCaps">false</item>
</style>

这是它现在的样子:

所以:我的按钮正在应用样式,但不是 TextView。关于为什么我的自定义字体没有应用于应用程序中的所有项目的任何想法?

【问题讨论】:

  • 您提供的有问题的链接对您的问题非常有帮助。
  • 我知道,我认为我的解决方案在那里......但是当我创建一个从 Application 扩展的类时,我无法让它工作,因为它说我的类从未使用过......
  • 在我的答案中查看更多链接,似乎很有帮助,还有一件事我的第一个链接真的更好,谢谢

标签: android android-fonts


【解决方案1】:

似乎您在styles.xml 中使用的是android:fontFamily 而不是android:typeface

尝试替换

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:fontFamily">default</item>
</style>

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:typeface">default</item>
</style>

【讨论】:

  • 我如何将它与我的应用程序连接起来?谁从它延伸出来?
  • 通过扩展Application,您只是创建了应用程序Application 类的子类。所以,你不需要连接它。
  • 什么说它从未使用过?
  • 您是否还按照同一篇 SO 帖子中的建议在应用程序的 res -&gt; values -&gt; styles.xml 文件的 &lt;style name="AppTheme" parent="AppBaseTheme"&gt; 中添加了 &lt;item name="android:typeface"&gt;default&lt;/item&gt; 行?
  • 是的,它也不起作用。这就是我在编辑中所做的... :(
【解决方案2】:

写一个类

public class MyApp extends Application{
// Put the onCreate code as you obtained from the post link you reffered
}

现在接下来的事情是在 AndroidManifest.xml 中为应用程序标签命名您的应用程序类。在这种情况下,它是 MyApp

<application
android:name=".MyApp"
...
>
...
</application>

所以每当打开应用程序时,都会调用 MyApp 类的 onCreate 方法,并设置字体。

更新 将字体文件放在 assets/fonts/your_font_file.ttf 下

将此行放在应用程序类(MyApp)的 onCreate 方法下

TypefaceUtil.overrideFont(getApplicationContext(), "SERIF", "fonts/your_font_file.ttf");

TypefaceUtil 的源文件

public class TypefaceUtil {

    /**
     * Using reflection to override default typeface
     * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
     *
     * @param context                    to work with assets
     * @param defaultFontNameToOverride  for example "monospace"
     * @param customFontFileNameInAssets file name of the font from assets
     */
    public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {

        final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Map<String, Typeface> newMap = new HashMap<String, Typeface>();
            newMap.put("serif", customFontTypeface);
            try {
                final Field staticField = Typeface.class
                        .getDeclaredField("sSystemFontMap");
                staticField.setAccessible(true);
                staticField.set(null, newMap);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
                defaultFontTypefaceField.setAccessible(true);
                defaultFontTypefaceField.set(null, customFontTypeface);
            } catch (Exception e) {
                Log.e(TypefaceUtil.class.getSimpleName(), "Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
            }
        }
    }
}

现在更新你的 style.xml 文件

将包含在清单文件中的活动的以下行放入您的样式

  <item name="android:typeface">serif</item>

希望对你有帮助

【讨论】:

  • 请告诉我您正在测试的 Android 操作系统版本。我在棒棒糖中观察到,我们需要制作更多的 tweeks
  • Lollipop 及之前安卓版本的解决方案请查看以下链接:(stackoverflow.com/a/36206275/2268466)
  • 它会更改 toast 消息中的所有应用程序字体,警报对话框,我不想在此用户自定义字体
  • 我有一个疑问,许多制造商允许用户从设置中更改系统范围内的字体,这种更改是否也会覆盖我们以编程方式设置的字体类型?
  • 设置多个字体怎么样?
【解决方案3】:

首先,创建一个覆盖您想要自定义的任何视图的新类。 (例如,想要一个带有自定义字体的按钮?扩展 Button)。例如:

public class CustomButton extends Button {
    private final static int ROBOTO = 0;
    private final static int ROBOTO_CONDENSED = 1;

    public CustomButton(Context context) {
        super(context);
    }

    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        parseAttributes(context, attrs); //I'll explain this method later
    }

    public CustomButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        parseAttributes(context, attrs);
    }
}

现在,如果您没有,请在res/values/attrs.xml 下添加一个 XML 文档,然后添加:

<resources>
    <!-- Define the values for the attribute -->
    <attr name="typeface" format="enum">
        <enum name="roboto" value="0"/>
        <enum name="robotoCondensed" value="1"/>
    </attr>

    <!-- Tell Android that the class "CustomButton" can be styled, 
         and which attributes it supports -->
    <declare-styleable name="CustomButton">
        <attr name="typeface"/>
    </declare-styleable>
</resources>

好的,那么,让我们回到之前的 parseAttributes() 方法:

private void parseAttributes(Context context, AttributeSet attrs) {
    TypedArray values = context.obtainStyledAttributes(attrs, R.styleable.CustomButton);

    //The value 0 is a default, but shouldn't ever be used since the attr is an enum
    int typeface = values.getInt(R.styleable.CustomButton_typeface, 0);

    switch(typeface) {
        case ROBOTO: default:
            //You can instantiate your typeface anywhere, I would suggest as a 
            //singleton somewhere to avoid unnecessary copies
            setTypeface(roboto); 
            break;
        case ROBOTO_CONDENSED:
            setTypeface(robotoCondensed);
            break;
    }

    values.recycle();
}

现在一切就绪。您可以为任何东西添加更多属性(您可以为字体样式添加另一个属性——粗体、斜体等),但现在让我们看看如何使用它:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:custom="http://schemas.android.com/apk/res/com.yourpackage.name"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <com.yourpackage.name.CustomButton
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Me!"
        custom:typeface="roboto" />

</LinearLayout>

xmlns:custom 行实际上可以是任何东西,但约定如上所示。重要的是它是独一无二的,这就是使用包名称的原因。现在您只需为属性使用custom: 前缀,为android 属性使用android: 前缀。

最后一件事:如果您想在样式中使用它 (res/values/styles.xml),您应该添加 xmlns:custom 行。只需引用不带前缀的属性名称:

<style name="MyStyle>
    <item name="typeface">roboto</item>
</style>

【讨论】:

    【解决方案4】:

    如果您关注第一个主题,这应该可以:Here

    是的,有反射。这有效(based on this answer):

    (注意:由于缺乏对自定义字体的支持,这是一种解决方法,因此,如果您想改变这种情况,请在此处为 android 问题投票)。注意:不要在这个问题上留下“我也是”cmets,当你这样做时,每个盯着它的人都会收到一封电子邮件。所以请给它加星标。

    import java.lang.reflect.Field;
    import android.content.Context;
    import android.graphics.Typeface;
    
    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();
        }
    }
    }
    

    然后您需要重载几个默认字体,例如在应用程序类中:

    public final class Application extends android.app.Application {
        @Override
        public void onCreate() {
            super.onCreate();
            FontsOverride.setDefaultFont(this, "DEFAULT", "MyFontAsset.ttf");
            FontsOverride.setDefaultFont(this, "MONOSPACE", "MyFontAsset2.ttf");
            FontsOverride.setDefaultFont(this, "SERIF", "MyFontAsset3.ttf");
            FontsOverride.setDefaultFont(this, "SANS_SERIF", "MyFontAsset4.ttf");
        }
    }
    

    当然,如果您使用相同的字体文件,您可以对此进行改进以仅加载一次。

    但是我倾向于只覆盖一个,例如“MONOSPACE”,然后设置一种样式以强制该字体字体应用范围:

    <resources>
        <style name="AppBaseTheme" parent="android:Theme.Light">
        </style>
    
        <!-- Application theme. -->
        <style name="AppTheme" parent="AppBaseTheme">
            <item name="android:typeface">monospace</item>
        </style>
    </resources>
    

    API 21 Android 5.0

    我调查了 cmets 中的报告,它不起作用,并且似乎与主题 android:Theme.Material.Light 不兼容。

    如果该主题对您不重要,请使用较旧的主题,例如:

    <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
        <item name="android:typeface">monospace</item>
    </style>
    

    【讨论】:

      【解决方案5】:

      编辑

      uk.co.chrisjenx:calligraphy Lib 不再为最新的 android 版本维护,现在可以替代 https://github.com/InflationX/Calligraphy

      dependencies {
          implementation 'io.github.inflationx:calligraphy3:3.1.1'
          implementation 'io.github.inflationx:viewpump:2.0.3'
      }
      

      将您的自定义字体添加到资产/

      用法

      默认字体

      使用 CalligraphyConfig 在您的 Application 类中的 #onCreate() 方法中定义您的默认字体,并将其传递给您添加到 ViewPump 构建器的 CalligraphyInterceptor。

      @Override
      public void onCreate() {
          super.onCreate();
          ViewPump.init(ViewPump.builder()
              .addInterceptor(new CalligraphyInterceptor(
                      new CalligraphyConfig.Builder()
                          .setDefaultFontPath("fonts/Roboto-RobotoRegular.ttf")
                          .setFontAttrId(R.attr.fontPath)
                          .build()))
              .build());
          //....
      }
      

      Inject into Context: Wrap the Activity Context:

      @Override
      protected void attachBaseContext(Context newBase) {
          super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase));
      }
      

      自定义样式

      <style name="TextViewCustomFont">
          <item name="fontPath">fonts/RobotoCondensed-Regular.ttf</item>
      </style>
      

      主题

      <style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">
          <item name="android:textViewStyle">@style/AppTheme.Widget.TextView</item>
      </style>
      
      <style name="AppTheme.Widget"/>
      
      <style name="AppTheme.Widget.TextView" parent="android:Widget.Holo.Light.TextView">
          <item name="fontPath">fonts/Roboto-ThinItalic.ttf</item>
      </style>
      

      解决方案下的开发人员不再维护


      在 android:Calligraphy 中有一个很棒的自定义字体库
      这是一个如何使用它的示例。

      在 Gradle 中,您需要将此行放入应用的 build.gradle 文件中:

              dependencies {
                  compile 'uk.co.chrisjenx:calligraphy:2.2.0'
              }
      

      然后做一个扩展Application的类,写下这段代码:

              public class App extends Application {
                  @Override
                  public void onCreate() {
                      super.onCreate();
      
                      CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                                      .setDefaultFontPath("your font path")
                                      .setFontAttrId(R.attr.fontPath)
                                      .build()
                      );
                  }
              } 
      

      您应该在 assets/ 上创建一个“新目录”“字体”(见下文),因此在该代码中“您的字体路径”应该是“fonts/SourceSansPro-Regular.ttf”。 (只是“字体...”而不是“/fonts..”或“assets..”)

      并且在activity类中把这个方法放在onCreate之前:

              @Override
              protected void attachBaseContext(Context newBase) {
                  super.attachBaseContext(CalligraphyContextWrapper.wrap(newBase));
              }
      

      你的清单文件最后应该是这样的:

              <application
                 .
                 .
                 .
                 android:name=".App">
      

      它会将整个活动更改为您的字体!简单干净!

      在资产上,您应该右键单击新建目录,将其称为“字体”。在finder中将.ttf字体文件放在那里。

      另外不要忘记在 attrs.xml 中添加以下两行,如果您没有 attrs.xml 文件,请在 values.xml 中创建新文件

       <attr format="string" name="fontPath"/> 
          <item name="calligraphy_tag_id" type="id"/>
      

      【讨论】:

      • 我正在使用 ttf,但我非常确定 .otf 也可以使用,并且是放置在 assets 文件夹中的最佳位置。
      • 把它放在扩展应用程序类 CalligraphyConfig.initDefault(new CalligraphyConfig.Builder() .setDefaultFontPath("fonts/GOTHAM-MEDIUM.ttf") .setFontAttrId(R.attr.fontPath) .build() );也不要忘记在 values.xml 中添加以下两行
      • 嗨@rajesh!您应该单击“编辑”并将其添加到您的最佳答案中!你是对的,它应该是 .ttf 文件,对不起。
      • 您可以尽可能多地使用片段。这样活动的数量就会减少。
      • @Pawan 一步到位 - 我定义了一个简单的基类,其中实现了 attachBaseContext(..),然后我的所有项目 Activity 类(我想要自定义字体的地方)扩展了该基类跨度>
      【解决方案6】:

      我也尝试过字体覆盖,但最终它不是一个可靠的解决方案,遗憾的是,覆盖字体需要更多的时间。您可以等待带有自定义字体的 Android O 出来,也可以使用第三方库。

      我遇到的最后一个解决方案是这个库 Caligraphy ,它很容易启动,让您可以使用任意数量的字体。在检查它的源代码时,我明白为什么只是覆盖字体不起作用所以即使你不打算使用它我建议你通读一遍..

      祝你好运

      【讨论】:

      • 是的……也许吧。无论如何,如果您找到此问题背后的原因,请告诉我们,非常感谢。即使阅读底层代码,我也找不到解决方案。
      【解决方案7】:

      试试下面的代码,它对我有用,希望对你也有帮助。

      public class BaseActivity extends AppCompatActivity {
      
      private Typeface typeace;
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          // TODO Auto-generated method stub
          super.onCreate(savedInstanceState);
          typeace = Typeface.createFromAsset(getAssets(), getResources().getString(R.string.font_name));
      }
      
      @Override
      protected void onStart() {
          // TODO Auto-generated method stub
          super.onStart();
          overrideFonts(this,getWindow().getDecorView());
      }
      
      private void overrideFonts(final Context context, final View v) {
          try {
              if (v instanceof ViewGroup) {
                  ViewGroup vg = (ViewGroup) v;
                  for (int i = 0; i < vg.getChildCount(); i++) {
                      View child = vg.getChildAt(i);
                      overrideFonts(context, child);
               }
              } else if (v instanceof TextView) {
                  ((TextView) v).setTypeface(typeace);
              } else if (v instanceof EditText ) {
                  ((EditText) v).setTypeface(typeace);
              } else if (v instanceof Button) {
                  ((Button) v).setTypeface(typeace);
              }
          } catch (Exception e) {
       }
       }
      }
      

      现在将此 BaseActivity 扩展到您的任何 Activity,或者如果您正在使用,您可以为 Fragment 创建相同的类。

      注意:- 如果您想设置一些不同的视图字体,那么您必须以编程方式进行设置,如下所示

      private Typeface typeface;
      typeface = Typeface.createFromAsset(getAssets(), getResources().getString(R.string.font_name_bold));
      tvUserName.setTypeface(typeface);
      

      所以试试看,如果我能进一步帮助你,请告诉我

      【讨论】:

        【解决方案8】:

        我所做的只是:

        1:在RES文件夹中添加“新资源目录”,从给定的下拉列表中选择RESOURCE TYPE为“字体”,将新目录命名为“字体”并保存。

        2:将我的“custom_font.ttf”添加到刚刚创建的 FONT 文件夹中。

        3:在 STYLES.XML 的应用程序基础主题中添加了我的自定义字体

        完成。

        【讨论】:

        • 您还必须创建一个字体系列。之后它对我有用。详情在这里:developer.android.com/guide/topics/ui/look-and-feel/…
        • 它对我有用,而无需创建字体系列。但是,我必须使用 Gradle 版本 > 3 并构建工具和支持库设置为 27> @keybee
        • 对我来说效果很好,即使没有字体系列
        • 你知道如何以编程方式更改它吗?
        • @majov 检查#Rajeesh 上面的答案。这应该对你有帮助!
        【解决方案9】:

        您现在可以使用 android SDK 进行操作,正如 Android 开发者官方 youtube 频道在 set/2017 here 中发布的那样。

        需要 API 级别 23 及以上。

        您只需将字体文件放在res/font 文件夹中并在TextView 中引用它们,以防您需要具有android:fontFamily 属性的特定字体。

        如果您想在整个应用中使用基本字体,只需输入

        <item name="android:fontFamily">@font/yourfontname</item> 
        

        在你的styles.xml

        您也可以从 Android Studio 下载自定义字体,如果需要,也可以随时随地下载。所有这些您都可以在上面的视频中找到详细信息。

        【讨论】:

        • 此选项适用于 API 26 及更高版本。不是 16+
        • 如何修复 API 23 + ?
        【解决方案10】:

        在主文件夹中创建资产文件夹。在其中添加字体文件夹。在字体文件夹中添加您的 .ttf 文件。

        在您的应用主题中添加以下内容:

         <item name="android:fontFamily">@font/roboto_regular</item>
            <item name="fontFamily">@font/roboto_regular</item>
        

        将类创建为 TypefaceUtil

         import android.content.Context;
        import android.graphics.Typeface;
        import android.util.Log;
        
        import java.lang.reflect.Field;
        
        public class TypefaceUtil {
        
            /**
             * Using reflection to override default typeface
             * NOTICE: DO NOT FORGET TO SET TYPEFACE FOR APP THEME AS DEFAULT TYPEFACE WHICH WILL BE OVERRIDDEN
             * @param context to work with assets
             * @param defaultFontNameToOverride for example "monospace"
             * @param customFontFileNameInAssets file name of the font from assets
             */
            public static void overrideFont(Context context, String defaultFontNameToOverride, String customFontFileNameInAssets) {
                try {
                    final Typeface customFontTypeface = Typeface.createFromAsset(context.getAssets(), customFontFileNameInAssets);
        
                    final Field defaultFontTypefaceField = Typeface.class.getDeclaredField(defaultFontNameToOverride);
                    defaultFontTypefaceField.setAccessible(true);
                    defaultFontTypefaceField.set(null, customFontTypeface);
                } catch (Exception e) {
                    Log.e("Can not set","Can not set custom font " + customFontFileNameInAssets + " instead of " + defaultFontNameToOverride);
                }
            }
        }
        

        在应用程序类或 Launcher 活动中调用它

                TypefaceUtil.overrideFont(getApplicationContext(), "fonts/roboto_regular.ttf", "fonts/roboto_regular.ttf"); // font from assets: "assets/fonts/Roboto-Regular.ttf
        

        【讨论】:

          【解决方案11】:

          Android 提供更简单和最佳的解决方案,支持库 26+ 支持 API 级别 14。 Fonts in XML 它还支持font family选项。 必需的进口: implementation "com.android.support:support-compat:&lt;26+ version&gt;"

          按照这些简单的步骤,字体系列将毫无障碍地应用到您的应用中:

          1. res 中创建一个 font 目录
          2. 将字体文件粘贴到 font
          3. 右键单击字体文件夹并转到新建 > 字体资源文件。将出现“新建资源文件”窗口。
          4. 添加以下属性
          <?xml version="1.0" encoding="utf-8"?>
          <font-family xmlns:android="http://schemas.android.com/apk/res/android">
              <font
                  android:fontStyle="normal"
                  android:fontWeight="400"
                  android:font="@font/lobster_regular" />
              <font
                  android:fontStyle="italic"
                  android:fontWeight="400"
                  android:font="@font/lobster_italic" />
          </font-family>
          
          1. 在上面的 xml 文件中。 app 仅用于使用支持库。否则,如果您的应用针对 API 级别 26+,您可以使用 android
          2. 现在转到您的styles.xml 并将下面的行放在您的主要样式中。
            <item name="android:fontFamily">@font/opensans</item>
            
          3. 重要提示:只有在使用支持库时才使用 AppCompatActivity
          4. 或使用下面以编程方式设置字体

            view.setTypeface(ResourcesCompat.getFont(context, R.font.opensans));
            

          【讨论】:

          • 这种方式适用于当前的 Android 字体资源功能。谢谢。
          【解决方案12】:

          kotlin 的解决方法是这样的

          解决方案的要点https://gist.github.com/Johnyoat/040ca5224071d01b3f3dfc6cd4d026f7

          第一步

          将字体文件放在 assets/fonts/your_font_file.ttf 下 并创建一个名为 TypeFaceUtil 的 kotlin 类

             object TypefaceUtil{
          
              fun overridefonts(context: Context, defaultFontToOverride:String, customFontFileNameInAssets:String){
                  try {
                      val customTypeface = Typeface.createFromAsset(context.assets,customFontFileNameInAssets)
                      val defaultTypefaceField = Typeface::class.java.getDeclaredField(defaultFontToOverride)
                      defaultTypefaceField.isAccessible = true
                      defaultTypefaceField.set(null,customTypeface)
                  }catch (e:Exception){
                      Timber.e("Cannot set font $customFontFileNameInAssets instead of $defaultFontToOverride")
                  }
              }
          }
          

          第二步 然后在你的onCreate

          TypefaceUtil.overridefonts(this,"SERIF","fonts/font_file.ttf")
          

          第三步

          将此添加到您的样式中

          <item name="android:typeface">serif</item>
          

          【讨论】:

            【解决方案13】:
            1. 一开始,你应该右键点击你的项目资源,名称为res,然后从new选项中选择Android Resource Directory,然后从Resource type中选择font,然后按OK,这将创建字体目录将您的字体放入其中。

            1. 把你的.ttf字体文件放在那里。

            1. 转到以下路径res/values/styles.xml中存在的项目样式文件 并添加这样的样式:

              <style name="SansSerifFont">
                  <item name="android:fontFamily">sans-serif</item>
              </style>
              
              <style name="OpenSansFont">
                  <item name="android:fontFamily">@font/open_sans</item>
              </style>
              
              <style name="IranianSansFont">
                  <item name="android:fontFamily">@font/iranian_sans</item>
              </style>
              
              <style name="BYekanFont">
                  <item name="android:fontFamily">@font/b_yekan</item>
              </style>
              
              <style name="DroidArabicFont">
                  <item name="android:fontFamily">@font/droid_arabic</item>
              </style>
              
            2. 转到您的代码并编写一个这样的类来更改整个应用程序的字体:

              public class AppFontManager {
              
                  private AppCompatActivity appCompatActivity;
              
                  public static final String SANS_SERIF_APP_FONT = "sans_serif";
                  public static final String B_YEKAN_APP_FONT = "b_yekan";
                  public static final String DROID_ARABIC_APP_FONT = "droid_arabic";
                  public static final String IRANIAN_SANS_APP_FONT = "iranian_sans";
                  public static final String OPEN_SANS_APP_FONT = "open_sans";
              
                  public AppAppearanceManager(AppCompatActivity appCompatActivity) {
                      this.appCompatActivity = appCompatActivity;
                  }
              
                  public void setFont(String fontName){
              
                      switch (fontName){
              
                          case SANS_SERIF_APP_FONT:{
                              appCompatActivity.getTheme().applyStyle(R.style.SansSerifFont, true);
                              break;
                          }
              
                          case B_YEKAN_APP_FONT:{
                              appCompatActivity.getTheme().applyStyle(R.style.BYekanFont, true);
                              break;
                          }
              
                          case DROID_ARABIC_APP_FONT:{
                              appCompatActivity.getTheme().applyStyle(R.style.DroidArabicFont, true);
                              break;
                          }
              
                          case IRANIAN_SANS_APP_FONT:{
                          appCompatActivity.getTheme().applyStyle(R.style.IranianSansFont, true);
                              break;
                          }
              
                          case OPEN_SANS_APP_FONT:{
                              appCompatActivity.getTheme().applyStyle(R.style.OpenSansFont, true);
                              break;
                          }
                      }
                  }
              }
              

              因为每个活动需要单独设置字体,我更喜欢为它写一个类以获得更简洁的代码。

            3. 然后在activity onCreatesuper.onCreate(savedInstanceState)之前调用类方法:

              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  new AppAppearanceManager(this).setFont(APP_DEFAULT_FONT);
                  super.onCreate(savedInstanceState);
              // Do you stuff there...
              }
              

              请记住,如果您想在运行时更改字体,请在SharedPreferences 等中写入选定的字体,然后将选定的字体传递给所有活动setFont,如上所示。

            【讨论】:

              【解决方案14】:

              字体名称应为小写,以便在应用程序和工作中显示。

              【讨论】:

                【解决方案15】:

                这就是我将字体 ttf 应用到整个应用程序的方式

                1.在res目录下创建一个名为font的目录

                2. 复制字体 ttf 例如此字体目录中的 varela.ttf

                3.检查AndroidManifest.xml中的主题

                    <application
                        android:theme="@style/Theme.MyAppTheme">
                        <activity
                            ......
                        </activity>
                    </application>
                

                4. 进入 values 目录中的 Themes.xml 并在 AndroidManifest.xml 中引用的基本主题样式中添加带有 item 标记的字体

                    <resources xmlns:tools="http://schemas.android.com/tools">
                        <!-- Base application theme. -->
                        <style name="Theme.MyAppTheme"
                          parent="Theme.MaterialComponents.DayNight.DarkActionBar">
                          <item name="android:fontFamily">@font/varela</item>
                        </style>
                    </resources>
                

                【讨论】:

                  猜你喜欢
                  • 2011-11-28
                  • 2012-08-30
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2012-08-04
                  • 2018-03-24
                  • 2011-02-12
                  • 1970-01-01
                  相关资源
                  最近更新 更多