【问题标题】:How to use custom font in a project written in Android Studio如何在 Android Studio 编写的项目中使用自定义字体
【发布时间】:2015-02-19 17:48:49
【问题描述】:

我尝试在 Android Studio 中使用自定义字体,就像在 Eclipse 中一样。但不幸的是无法弄清楚将“资产”文件夹放在哪里!

【问题讨论】:

标签: android android-studio


【解决方案1】:

2021 年更新:

res 文件夹中创建一个名为 font 的文件夹并复制您的字体

所有字体名称只能是:小写 a-z、0-9 或下划线。

<TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fontFamily="@font/abc_font" />

用于编程用途:

textView.setTypeface(ResourcesCompat.getFont(context, R.font.abc_font))

对于 Android Studio 4.2+,现在甚至还有一个菜单选项:

【讨论】:

  • 任何从资产加载自定义字体的人都应该注意,Android 5.0 中存在一些字体无法加载的错误。虽然此问题在 Android 5.1 中已修复,但支持 5.0 的解决方法是重新编写 ttf 字体。有关更多信息,请参阅此问题stackoverflow.com/questions/27269264/…
  • 第二个选项对我来说效果很好。谢谢!
  • 我用 this.getContext().getApplicationContext().getAssets() 找到目录(android studio 2.1)
  • @kuthue onCreate() 很好。如果您想在用户使用应用程序时更改字体,您可以将其放在您希望更改的位置。这也适用于按钮
  • 如何将整个项目的默认字体设置为我添加的自定义字体?这就是第一个代码示例正在做的事情吗?
【解决方案2】:

  1. 选择文件>新建>文件夹>资产文件夹

  2. 点击完成

  3. 右键单击assets并创建一个名为fonts

  4. 的文件夹
  5. 将您的字体文件放入 assets > fonts

  6. 使用下面的代码更改 textView 的字体

    TextView textView = (TextView) findViewById(R.id.textView);
    Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/yourfont.ttf");
    textView.setTypeface(typeface);
    

【讨论】:

  • 如何在xml中使用这个?
  • 本教程介绍了如何在 XML 中使用它:stacktips.com/tutorials/android/…
  • @Suisse 支持库 26 在运行 API 版本 14 及更高版本的设备上完全支持此功能link
【解决方案3】:

有很多方法可以在字段上设置自定义字体系列,我正在使用如下。

要将字体添加为资源,请在 Android Studio 中执行以下步骤:

1) 右键单击​​ res 文件夹并转到 New > Android 资源目录。将出现“新建资源目录”窗口。

2) 在“资源类型”列表中,选择字体,然后单击“确定”。

注意:资源目录的名称必须是字体。

3) 在字体文件夹中添加您的字体文件。

在您的 xml 文件中的所需视图中添加字体:

注意:但您需要以下内容:

  1. Android Studio 以上到 3.0 canary。

  2. 您的 Activity 扩展了 AppCompatActivity。

  3. 像这样更新你的 Gradle 文件:

    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    defaultConfig {        
        minSdkVersion 19
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

buildtoolsVersion 高于 26,最低 targetSdkVersion 需要 26

  1. 在 build.gradle 文件中添加依赖项:
classpath 'com.android.tools.build:gradle:3.0.0-beta4'
  1. gradle-wrapper.properties:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.1-all.zip

【讨论】:

    【解决方案4】:

    我认为我们可以使用 Google 字体,而不是下载 .ttf 文件。这很容易实现。只有您必须遵循这些步骤。 步骤 1) 打开项目的 layout.xml 并在属性中选择文本视图的字体系列(参考屏幕截图)

    步骤 2) 如果您的字体不存在,请在字体系列中选择更多字体.. 选项。然后您将看到一个新窗口将打开,您可以在其中输入所需的字体并从该列表中选择所需的字体,即常规、粗体、斜体等。如下图所示。

    第 3 步) 然后您会看到 /res 文件夹中会自动生成一个字体文件夹,其中包含您选择的字体 xml 文件。

    那么就可以直接在xml中使用这个字体族了

          android:fontFamily="@font/josefin_sans_bold"
    

    或以编程方式,您可以使用

    来实现此目的
      Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
      fontText.setTypeface(typeface);
    

    【讨论】:

    • 这不是问题的答案。并非所有字体都可以在 Google 字体中使用。
    • 不错的答案!如果您在列表中找不到您的字体 - 将其加载到 assets 文件夹中或通过 xml 定义它
    【解决方案5】:

    您好,我们有一个更好的方法可以同时在 Android 上的 EditTexts 和 TextViews 上应用字体并将其应用到整个项目中。

    首先你需要创建字体文件夹。以下是步骤。

    1:转到(项目文件夹)然后app>src>main

    2:在主文件夹中创建名为“assets/fonts”的文件夹。

    3:将字体放入字体文件夹。在这里我有'MavenPro-Regular.ttf'

    以下是在 EditText 上应用自定义字体的步骤,使用这种方法,您可以在每个输入上应用字体。

    1:创建一个 MyEditText 类(您的首选名称...)

    2 : 扩展 EditText

    3 : 应用你的字体

    这里是代码示例;

    public class MyEditText extends EditText {
    
        public MyEditText(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            init();
        }
    
        public MyEditText(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public MyEditText(Context context) {
            super(context);
            init();
        }
    
        private void init() {
            if (!isInEditMode()) {
                Typeface tf = Typeface.createFromAsset(getContext().getAssets(), "fonts/MavenPro-Regular.ttf");
                setTypeface(tf);
            }
        }
    
    }
    

    这里是如何使用它的代码。

    MyEditText editText = (MyEditText) findViewById(R.id.editText);
    
    editText.setText("Hello");
    

    或在您的 xml 文件中

       <MyEditText
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="#fff"
        android:textSize="16dp"
        android:id="@+id/editText"
        />
    

    【讨论】:

    • 那个类在运行时给了我那个错误:Error inflating class MyEditText
    • 参考此链接您可能会发现一些提示如何解决错误。
    • 使用当前版本,我认为您需要将其更改为“扩展 AppCompatEditText”。
    【解决方案6】:

    借助支持库 26.0(和 Android O),可以通过以下方式轻松地从资源中加载字体:

    Typeface typeface = ResourcesCompat.getFont(Context context, int fontResourceId) 
    

    Docs for the method.

    更多信息可以找到here.

    【讨论】:

      【解决方案7】:

      我想为 Android-O 和 Android Studio 2.4 添加我的答案

      1. res 文件夹下创建名为 font 的文件夹。下载您想添加到项目示例中的各种字体Google fonts

      2. 在您的 xml 用户字体系列中

        示例:

        <TextView
            android:fontFamily="@font/indie_flower"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="10dp"
            android:text="@string/sample_text" />
        

      3.如果您希望它以编程方式使用以下代码

      Typeface typeface = getResources().getFont(R.font.indie_flower);
      textView.setTypeface(typeface);
      

      更多信息请点击我的博客链接Font styles for Android with Android Studio 2.4

      【讨论】:

      • 请注意,如果您想宣传自己的产品/博客,您必须披露您的隶属关系,否则您的回答可能会被标记为垃圾邮件。请阅读How to not be a spammer
      • 是的@PetterFriberg
      【解决方案8】:

      根据 Android O 中提供的新功能,font resources in XML 作为新功能可用。

      要将字体添加为资源,请在 Android Studio 中执行以下步骤:

      1) 右击res文件夹,进入新建> Android资源目录。将出现“新建资源目录”窗口。

      2) 在资源类型列表中,选择字体,然后点击确定。

      注意:资源目录的名称必须是字体。

      3) 在字体文件夹中添加您的字体文件。

      您可以借助新的资源类型字体来访问字体资源。例如,要访问字体资源,请使用 @font/myfont 或 R.font.myfont。

      例如。 Typeface typeface = getResources().getFont(R.font.myfont); textView.setTypeface(typeface);

      【讨论】:

      • 应该是 ResourcesCompat.getFont(context, R.font.your_font)
      【解决方案9】:

      您可以使用简单易用的EasyFonts 第三方库为您的TextView 设置各种自定义字体。通过使用这个库,您不必担心下载字体并将其添加到 assets/fonts 文件夹中。还有关于字体对象的创建。您也无需创建资产文件夹。

      简单地说:

      TextView myTextView = (TextView)findViewById(R.id.myTextView);
      myTextView.setTypeface(EasyFonts.robotoThin(this));
      

      这个库提供了许多类型的字体。

      【讨论】:

        【解决方案10】:
        1. 在 Project -> app(或您的应用名称)-> src -> main -> 右键单击​​ -> New -> Directory 中创建文件夹资产。
        2. 然后在 assets 中创建一个名为“fonts”的新目录。

        将字体分配给 textView:

        TextView textView = (TextView) findViewById(R.id.your_textView);
        
        final Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/your_font_name");
        

        your_font_name 包括字体扩展名。

        【讨论】:

          【解决方案11】:

          第一次在字体文件夹中添加 font.ttf 文件。然后在 onCreate 方法中添加这一行

              Typeface typeface = ResourcesCompat.getFont(getApplicationContext(), R.font.myfont);
              mytextView.setTypeface(typeface);
          

          这是我的 xml

                      <TextView
                      android:id="@+id/idtext1"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:layout_marginTop="7dp"
                      android:gravity="center"
                      android:text="My Text"
                      android:textColor="#000"
                      android:textSize="10sp"
                  />
          

          【讨论】:

            【解决方案12】:

            如果您像我一样对 Android 非常陌生,这可能有点棘手。确保您致电:

            TextView myTextView = (TextView) findViewById(R.id.textView);
            Typeface typeface=Typeface.createFromAsset(getAssets(), "fonts/your font.ttf");
            myTextView.setTypeface(typeface);
            

            方法中的方法,例如onCreate

            【讨论】:

              【解决方案13】:

              要在运行 Android 4.1(API 级别 16)及更高版本的设备上使用 XML 字体功能,请使用支持库 26。有关使用支持库的更多信息,请参阅使用支持库部分。

              要将字体添加为资源,请在 Android Studio 中执行以下步骤:

              1. 右键单击 res 文件夹,然后转到 New > Android 资源目录。

                新资源目录窗口出现。

              2. 在“资源类型”列表中,选择字体,然后单击“确定”。

              3. 在字体文件夹中添加您的字体文件。

              创建字体系列 要创建字体系列,请在 Android Studio 中执行以下步骤:

              1. 右键单击字体文件夹并转到新建 > 字体资源文件。将出现“新建资源文件”窗口。

              2. 输入文件名,然后单击“确定”。新的字体资源 XML 在编辑器中打开。

              3. 将每个字体文件、样式和粗细属性包含在元素中。以下 XML 说明了在字体资源 XML 中添加与字体相关的属性: 如果您的 minSdkVersion 是 API 级别 26 或更高级别

              <?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>
              
              

              如果您的 minSdkVersion 低于 API 级别 26

              <?xml version="1.0" encoding="utf-8"?>
              <font-family xmlns:app="http://schemas.android.com/apk/res-auto">
                  <font
                      app:font="@font/lobster_italic"
                      app:fontStyle="normal"
                      app:fontWeight="400" />
              </font-family>
              

              然后你可以在任何地方像这样使用它

              android:fontFamily="@font/your_custom_font_file"
              

              【讨论】:

                【解决方案14】:

                Android 8.0 (API 26) 引入了与字体相关的新功能。

                1) 字体可以作为资源使用。

                2) 可下载的字体。

                如果你想在你的 android 应用程序中使用外部字体,你可以在 apk 中包含字体文件或配置可下载的字体。

                在 APK 中包含字体文件:您可以下载字体文件,将它们保存在 res/font filer 中,定义字体系列并在样式中使用字体系列。

                有关使用自定义字体作为资源的更多详细信息,请参阅http://www.zoftino.com/android-using-custom-fonts

                配置可下载字体:通过提供字体提供者详细信息来定义字体,添加字体提供者证书并在样式中使用字体。

                有关可下载字体的更多详细信息,请参阅http://www.zoftino.com/downloading-fonts-android

                【讨论】:

                • 另外,仅仅因为自定义/可下载字体是在 Android O (8.0) 中引入的,并不意味着它没有向后兼容性。请参阅有关如何实现自定义字体的官方文档。请注意,您可能还需要安装 Android Studio 3.0。
                【解决方案15】:

                我无法加载字体,因为我已将字体文件命名为 Poppins-Medium.tff,将其重命名为 poppins_medium.tff 对我有用。 其余步骤保持不变:

                • 在res文件夹下创建字体资源目录
                • 将您的 tff 文件复制并粘贴到该目录中
                • 然后使用 fontFamily 属性在 XML 中的 TextView 中使用。
                • 如果上述步骤不起作用,您可以使用此link 创建该字体的 FontFamily

                【讨论】:

                  【解决方案16】:

                  首先创建assets文件夹,然后在其中创建fonts文件夹。

                  然后你可以像下面这样从assetsdirectory 设置font

                  public class FontSampler extends Activity {
                      @Override
                      public void onCreate(Bundle icicle) {
                          super.onCreate(icicle);
                          setContentView(R.layout.main);
                  
                          TextView tv = (TextView) findViewById(R.id.custom);
                          Typeface face = Typeface.createFromAsset(getAssets(), "fonts/HandmadeTypewriter.ttf");
                  
                          tv.setTypeface(face);
                  
                          File font = new File(Environment.getExternalStorageDirectory(), "MgOpenCosmeticaBold.ttf");
                  
                          if (font.exists()) {
                              tv = (TextView) findViewById(R.id.file);
                              face = Typeface.createFromFile(font);
                  
                              tv.setTypeface(face);
                          } else {
                              findViewById(R.id.filerow).setVisibility(View.GONE);
                          }
                      }
                  } 
                  

                  【讨论】:

                    【解决方案17】:

                    现在有很多方法可以应用字体,其中一种最简单的方法就是这样, 1)右键单击res文件夹 转到新建 > Android 资源目录。

                    2) 从资源类型列表中选择字体,然后单击确定。

                    3) 将字体文件放入字体文件夹中。

                    【讨论】:

                      【解决方案18】:

                      将字体添加到 app/src/main/assets 的 assets 文件夹中 制作这样的自定义文本视图:

                      class CustomLightTextView : TextView {
                      
                      constructor(context: Context) : super(context){
                          attachFont(context)
                      }
                      constructor(context: Context, attrs: AttributeSet):    super(context, attrs){
                          attachFont(context)
                      }
                      constructor(context: Context, attrs: AttributeSet?,    defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
                          attachFont(context)
                      }
                      fun attachFont(context: Context) {
                          this.setTypeface(FontCache.getInstance().getLightFont(context))
                      }
                      

                      }

                      添加 FontCache :这样您就不必像这样一次又一次地创建字体:

                      class FontCache private constructor(){
                      
                      val fontMap = HashMap<String,Typeface>()
                      
                      companion object {
                          private var mInstance : FontCache?=null
                          fun getInstance():FontCache = mInstance?: synchronized(this){
                              return mInstance?:FontCache().also { mInstance=it }
                          }
                      }
                      
                      fun getLightFont(context: Context):Typeface?{
                          if(!fontMap.containsKey("light")){
                              Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf");
                              fontMap.put("light",Typeface.createFromAsset(context.getAssets(),"Gotham-Book.otf"))
                          }
                          return fontMap.get("light")
                      }
                      

                      }

                      你就完成了!

                      P.S.从android O,可以直接添加字体。

                      【讨论】:

                        【解决方案19】:

                        将字体放入资产文件夹 然后应用 fontfamily:''你的字体

                        【讨论】:

                          【解决方案20】:

                          为您的项目添加字体

                          要将字体添加为资源,请在 Android Studio 中执行以下步骤:

                          1 - 右键单击​​ res 文件夹并转到新建 > Android 资源目录。 将出现“新建资源目录”窗口。

                          2 - 在资源类型列表中,选择字体,然后单击确定。 3 - 只需简单的复制和粘贴即可将字体文件添加到字体文件夹中。请注意字体名称应为小写。

                          在 XML 布局中使用字体

                          <TextView
                              android:layout_width="wrap_content"
                              android:layout_height="wrap_content"
                              android:fontFamily="@font/lobster"/>
                          

                          为样式添加字体

                          <style name="customfontstyle" parent="@android:style/TextAppearance.Small">
                          <item name="android:fontFamily">@font/lobster</item>
                          </style>
                          

                          以编程方式使用字体

                          科特林:

                          val typeface = resources.getFont(R.font.myfont)
                          textView.typeface = typeface
                          

                          JAVA:

                          Typeface typeface = getResources().getFont(R.font.myfont);
                          textView.setTypeface(typeface);
                          

                          【讨论】:

                            【解决方案21】:

                            Kotlin 答案

                            如果你需要在代码端使用字体,你可以使用这个功能,它有版本代码控制。

                            fun getFontJarvisWhite(): Typeface {
                                return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) resources.getFont(R.font.jarvis_white)
                                else context?.let { ResourcesCompat.getFont(it, R.font.jarvis_white) }!!
                            }
                            

                            【讨论】:

                              【解决方案22】:

                              对于新读者

                              你可以使用这个库 Gloxey Custom Font Views

                              gradle 依赖

                                dependencies{
                                         compile 'io.gloxey.cfv:custom-font-views:1.0.2'
                                  }
                              

                              如何使用?

                              创建文件夹assets -> fonts。将您的字体复制到 fonts 文件夹中。

                              使用属性 app : font_name = "font_name_string" 在视图上应用字体。

                              示例

                                 <!--Font Names in srings.xml-->
                                     <string name="aadhunik">aadhunik.ttf</string>
                                     <string name="kung_fool">kungfool.ttf</string>
                                     <string name="skrova">skrova.otf</string>
                                     <string name="painting_in_the_sun_light">painting_in_the_sun_light.ttf</string>
                              
                                 <!--Include views in layout.xml-->
                                     <io.gloxey.cfv.CFTextView
                                     android:layout_width="match_parent"
                                     android:layout_height="wrap_content"
                                     android:gravity="center"
                                     android:text="Aadhunik"
                                     android:textColor="#ff00"
                                     android:textSize="40sp"
                                     app:font_name="@string/aadhunik" />
                              
                                     <io.gloxey.cfv.CFButton
                                     android:layout_width="match_parent"
                                     android:layout_height="wrap_content"
                                     android:text="Kung Fool"
                                     android:textColor="#154748"
                                     app:font_name="@string/kung_fool" />
                              
                                     <io.gloxey.cfv.CFEditText
                                     android:layout_width="match_parent"
                                     android:layout_height="wrap_content"
                                     android:gravity="center"
                                     android:text="Hello world"
                                     android:textSize="30sp"
                                     app:font_name="@string/skrova" />
                              
                                     <io.gloxey.cfv.CFCheckBox
                                     android:layout_width="wrap_content"
                                     android:layout_height="wrap_content"
                                     android:layout_gravity="center"
                                     android:text="Painting In The Sun Light"
                                     android:textSize="30sp"
                                     app:font_name="@string/painting_in_the_sun_light" />
                              

                              【讨论】:

                                猜你喜欢
                                • 2014-08-18
                                • 2013-11-28
                                • 1970-01-01
                                • 2016-02-20
                                • 1970-01-01
                                • 2022-09-24
                                • 1970-01-01
                                • 1970-01-01
                                • 2015-10-15
                                相关资源
                                最近更新 更多