简体   繁体   English

如何在 Android Studio 编写的项目中使用自定义字体

[英]How to use custom font in a project written in Android Studio

I was trying to use custom font in Android Studio as we did in Eclipse.我试图在 Android Studio 中使用自定义字体,就像我们在 Eclipse 中所做的那样。 But unfortunately could not figure out where to put the 'assets' folder!但不幸的是无法弄清楚“资产”文件夹放在哪里!

Update 2021: 2021 年更新:

Create a folder named font inside the res folder and copy your fontres文件夹中创建一个名为font的文件夹并复制您的字体

在此处输入图片说明

All font names must be only: lowercase az, 0-9, or underscore.所有字体名称只能是:小写 az、0-9 或下划线。

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

For programmatic use:用于程序化用途:

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

For Android Studio 4.2+ there's even now a menu option:对于 Android Studio 4.2+,现在甚至还有一个菜单选项:

在此处输入图片说明

https://i.stack.imgur.com/i6XNU.png

  1. Select File>New>Folder>Assets Folder选择文件>新建>文件夹>资产文件夹

  2. Click finish点击完成

  3. Right click on assets and create a folder called fonts右键单击资产并创建一个名为fonts的文件夹

  4. Put your font file in assets > fonts将您的字体文件放在assets > fonts

  5. Use code below to change your textView's font使用下面的代码来改变你的 textView 的字体

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

There are many ways to set custom font family on field and I am using like that below.有很多方法可以在现场设置自定义字体系列,我正在使用下面的方法。

To add fonts as resources, perform the following steps in the Android Studio:要将字体添加为资源,请在 Android Studio 中执行以下步骤:

1) Right-click the res folder and go to New > Android resource directory. 1) 右键单击​​ res 文件夹,然后转到新建 > Android 资源目录。 The New Resource Directory window appears.出现“新建资源目录”窗口。

2) In the Resource type list, select font, and then click OK. 2) 在资源类型列表中,选择字体,然后单击确定。

Note: The name of the resource directory must be font.注意:资源目录的名称必须是字体。

3) Add your font files in the font folder. 3) 在字体文件夹中添加您的字体文件。 在此处输入图片说明

Add font in desired view in your xml file:在您的 xml 文件中的所需视图中添加字体:

在此处输入图片说明

Note: But you required the following things for that:注意:但是您需要以下内容:

  1. Android Studio above to 3.0 canary. Android Studio 以上到 3.0 canary。

  2. Your Activity extends AppCompatActivity.您的 Activity 扩展了 AppCompatActivity。

  3. Update your Gradle file like that:像这样更新你的 Gradle 文件:

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

buildtoolsVersion above to 26 and minimum targetSdkVersion required 26 buildtoolsVersion高于 26 并且所需的最低targetSdkVersion 26

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

I think instead of downloading .ttf file we can use Google fonts.我认为我们可以使用 Google 字体代替下载 .ttf 文件。 It's very easy to implements.它很容易实现。 only you have to follow these steps.只有您必须遵循这些步骤。 step 1) Open layout.xml of your project and the select font family of text view in attributes (for reference screen shot is attached)步骤 1)打开项目的 layout.xml 和属性中文本视图的选择字体系列(附上参考屏幕截图) 在此处输入图片说明

step 2) The in font family select More fonts.. option if your font is not there.步骤 2)如果您的字体不存在,则在字体系列中选择更多字体.. 选项。 then you will see a new window will open, there you can type your required font & select the desired font from that list ie) Regular, Bold, Italic etc.. as shown in below image.然后您将看到一个新窗口将打开,您可以在那里输入所需的字体并从该列表中选择所需的字体,即)Regular、Bold、Italic 等。如下图所示。 在此处输入图片说明

step 3) Then you will observe a font folder will be auto generated in /res folder having your selected fonts xml file.步骤 3)然后您将观察到一个字体文件夹将在 /res 文件夹中自动生成,其中包含您选择的字体 xml 文件。

在此处输入图片说明

Then you can directly use this font family in xml as然后你可以直接在xml中使用这个字体系列作为

      android:fontFamily="@font/josefin_sans_bold"

or pro grammatically you can achieve this by using或者在编程上你可以通过使用来实现这一点

  Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);
  fontText.setTypeface(typeface);

Hello here we have a better way to apply fonts on EditTexts and TextViews on android at once and apply it in whole project.您好,我们有一种更好的方法可以同时在 android 上的 EditTexts 和 TextViews 上应用字体,并将其应用到整个项目中。

First of All you need to make fonts folder.首先,您需要制作字体文件夹。 Here are Steps.这是步骤。

1: Go to the (project folder) Then app>src>main 1:进入(项目文件夹)然后app>src>main

2: Create folders named 'assets/fonts' into the main folder. 2:在主文件夹中创建名为“assets/fonts”的文件夹。

3: Put your fonts into the fonts folder. 3:将你的字体放入字体文件夹。 Here I Have 'MavenPro-Regular.ttf'在这里我有“MavenPro-Regular.ttf”

Here are the Steps for applying custom fonts on EditText and using this approach you can apply fonts on every input.以下是在 EditText 上应用自定义字体的步骤,使用这种方法您可以在每个输入上应用字体。

1 : Create a Class MyEditText (your preferred name ...) 1:创建一个类 MyEditText(您的首选名称...)

2 : which extends EditText 2 :它扩展了 EditText

3 : Apply your font 3:应用你的字体

Here is code Example;这是代码示例;

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);
        }
    }

}

And in Here is the code how to use it.在这里是如何使用它的代码。

MyEditText editText = (MyEditText) findViewById(R.id.editText);

editText.setText("Hello");

Or in Your xml File或者在你的 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"
    />

With Support Library 26.0 (and Android O) fonts can be loaded from resource easily with:使用支持库 26.0(和 Android O)字体可以轻松地从资源加载: 在此处输入图片说明

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

Docs for the method . 该方法的文档

More info can be found here.更多信息可以在这里找到

I want to add my answer for Android-O and Android Studio 2.4我想为 Android-O 和 Android Studio 2.4 添加我的答案

  1. Create folder called font under res folder.res文件夹下创建名为font 的文件夹。 Download the various fonts you wanted to add to your project example Google fonts下载您想要添加到项目示例Google 字体中的各种字体

  2. Inside your xml user font family在您的 xml 用户字体系列中

    example :例子 :

     <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.If you want it to be in programmatic way use following code 3.如果您希望它以编程方式使用以下代码

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

for more information follow the link to my blog post Font styles for Android with Android Studio 2.4有关更多信息,请访问我的博客文章Font Styles for Android with Android Studio 2.4 的链接

As per new feature available in Android O, font resources in XML is avilable as new feature.根据 Android O 中提供的新功能,XML 中的字体资源可作为新功能使用。

To add fonts as resources, perform the following steps in the Android Studio:要将字体添加为资源,请在 Android Studio 中执行以下步骤:

1) Right-click the res folder and go to New > Android resource directory . 1) 右键单击res文件夹,然后转到New > Android resource directory The New Resource Directory window appears.出现“新建资源目录”窗口。

2) In the Resource type list, select font , and then click OK. 2) 在资源类型列表中,选择字体,然后单击确定。

Note: The name of the resource directory must be font.注意:资源目录的名称必须是字体。

3) Add your font files in the font folder. 3) 在字体文件夹中添加您的字体文件。

You can access the font resources with the help of a new resource type, font.您可以在新资源类型 font 的帮助下访问字体资源。 For example, to access a font resource, use @font/myfont, or R.font.myfont.例如,要访问字体资源,请使用 @font/myfont 或 R.font.myfont。

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

You can use easy & simple EasyFonts third party library to set variety of custom font to your TextView .您可以使用简单易用的EasyFonts第三方库为您的TextView设置各种自定义字体。 By using this library you should not have to worry about downloading and adding fonts into the assets/fonts folder.通过使用这个库,您不必担心下载字体并将其添加到 assets/fonts 文件夹中。 Also about Typeface object creation.还有关于字体对象的创建。 You will be free from creating asset folder too.您也无需创建资产文件夹。

Simply:简单地:

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

There are many type of fonts provided by this library.这个库提供了许多类型的字体。

  1. Create folder assets in Project -> app (or your app name) -> src -> main -> right click -> New -> Directory.在 Project -> app(或您的应用程序名称)-> src -> main -> 右键单击​​ -> New -> Directory 中创建文件夹资产。
  2. Then create a new directory inside assets called "fonts".然后在资产中创建一个名为“fonts”的新目录。

To assign the font to the textView:将字体分配给 textView:

TextView textView = (TextView) findViewById(R.id.your_textView);

final Typeface font = Typeface.createFromAsset(context.getAssets(), "fonts/your_font_name");

your_font_name includes font extension. your_font_name 包括字体扩展名。

1st add font.ttf file on font Folder. 1st 在字体文件夹中添加 font.ttf 文件。 Then Add this line in onCreate method然后在 onCreate 方法中添加这一行

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

And here is my xml这是我的 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"
        />

If you are very new to Android like I am this can be a little tricky.如果你像我一样对 Android 非常陌生,这可能有点棘手。 Make sure you call:确保您致电:

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

method within a method such as onCreate .方法中的方法,例如onCreate

Android 8.0 (API 26) introduced new features related to fonts. Android 8.0 (API 26) 引入了与字体相关的新功能。

1) Fonts can be used as resources. 1) 字体可以用作资源。

2) Downloadable fonts. 2) 可下载的字体。

If you want to use external fonts in your android application, you can either include font files in apk or configure downloadable fonts.如果你想在你的 android 应用程序中使用外部字体,你可以在 apk 中包含字体文件或配置可下载的字体。

Including font files in APK : You can download font files, save them in res/font filer, define font family and use font family in styles.在 APK 中包含字体文件:您可以下载字体文件,将它们保存在 res/font filer 中,定义字体系列并在样式中使用字体系列。

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

Configuring downloadable fonts : Define font by providing font provider details, add font provider certificate and use font in styles.配置可下载字体:通过提供字体提供者详细信息来定义字体,添加字体提供者证书并在样式中使用字体。

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

First create assets folder then create fonts folder in it.首先创建assets文件夹,然后在其中创建fonts文件夹。

Then you can set font from assets or directory like bellow :然后您可以从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);
        }
    }
} 

Now there are so many ways to apply font one of easiest way is like this, 1) Right-click the res folder go to New > Android resource directory.现在有很多方法可以应用字体,其中一种最简单的方法是这样,1) 右键单击​​ res 文件夹,转到 New > Android 资源目录。

2) From Resource type list, select font, and then click OK. 2) 从资源类型列表中,选择字体,然后单击确定。

3) Put your font files in the font folder. 3) 将您的字体文件放在字体文件夹中。

Add your fonts to assets folder in app/src/main/assets make a custom textview like this :将您的字体添加到 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))
}

} }

Add FontCache : So that you don't have to create typeface again and again like :添加 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")
}

} }

And you are done !大功告成!

PSFrom android O, you can directly add fonts. PS从android O,可以直接添加字体。

将字体放在资产文件夹中,然后应用 fontfamily:''your fonts

I could not load fonts because I had named my font file Poppins-Medium.tff, renaming it to poppins_medium.tff worked for me.我无法加载字体,因为我已将字体文件命名为 Poppins-Medium.tff,将其重命名为 poppins_medium.tff 对我有用。 Rest of the steps remained the same:其余步骤保持不变:

  • Create the font resource directory under res folder在res文件夹下创建字体资源目录
  • Copy and paste your tff file in that directory将您的 tff 文件复制并粘贴到该目录中
  • Then use in TextView in XML using fontFamily attribute.然后使用 fontFamily 属性在 XML 中的 TextView 中使用。
  • If above steps dont work, you can create a FontFamily of that font using this link如果上述步骤不起作用,您可以使用此链接创建该字体的 FontFamily

To use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, use the Support Library 26. For more information on using the support library, refer to the Using the support library section.要在运行 Android 4.1(API 级别 16)及更高版本的设备上使用 XML 中的字体功能,请使用支持库 26。有关使用支持库的更多信息,请参阅使用支持库部分。

To add fonts as resources, perform the following steps in the Android Studio:要将字体添加为资源,请在 Android Studio 中执行以下步骤:

  1. Right-click the res folder and go to New > Android resource directory.右键单击 res 文件夹,然后转到新建 > Android 资源目录。

    The New Resource Directory window appears.出现“新建资源目录”窗口。

  2. In the Resource type list, select font, and then click OK.在资源类型列表中,选择字体,然后单击确定。

  3. Add your font files in the font folder.在字体文件夹中添加您的字体文件。

Creating a font family To create a font family, perform the following steps in the Android Studio:创建字体系列要创建字体系列,请在 Android Studio 中执行以下步骤:

  1. Right-click the font folder and go to New > Font resource file.右键单击字体文件夹,然后转到新建 > 字体资源文件。 The New Resource File window appears.出现“新建资源文件”窗口。

  2. Enter the file name, and then click OK.输入文件名,然后单击“确定”。 The new font resource XML opens in the editor.新字体资源 XML 在编辑器中打开。

  3. Enclose each font file, style, and weight attribute in the element.在元素中包含每个字体文件、样式和粗细属性。 The following XML illustrates adding font-related attributes in the font resource XML: If your minSdkVersion is API level 26 and higher以下 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>

and if your minSdkVersion is lower than API level 26如果您的 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>

Then you can use it any where like this然后你可以在任何地方使用它

android:fontFamily="@font/your_custom_font_file"

Kotlin Answer科特林答案

If you need to use fonts in code side, you can use this function also it has version code control.如果你需要在代码端使用字体,你可以使用这个功能,它有版本代码控制。

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) }!!
}

Adding font to your project将字体添加到您的项目

To add fonts as resources, perform the following steps in the Android Studio:要将字体添加为资源,请在 Android Studio 中执行以下步骤:

1 - Right-click the res folder and go to New > Android resource directory. 1 - 右键单击​​ res 文件夹并转到新建 > Android 资源目录。 The New Resource Directory window appears.出现“新建资源目录”窗口。

2 - In the Resource type list, select font, and then click OK. 2 - 在资源类型列表中,选择字体,然后单击确定。 3 - Add your font files in the font folder just by a simple copy and paste. 3 - 只需通过简单的复制和粘贴,即可将您的字体文件添加到字体文件夹中。 note that the name of the fonts should be in lowercase.请注意,字体名称应为小写。

Using fonts in XML layouts在 XML 布局中使用字体

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

Adding fonts to style将字体添加到样式

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

Using fonts programmatically以编程方式使用字体

Kotlin:科特林:

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

JAVA:爪哇:

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

For new readers对于新读者

You can use this library Gloxey Custom Font Views你可以使用这个库Gloxey Custom Font Views

gradle dependency gradle 依赖

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

How to use?如何使用?

Create folder assets -> fonts .创建文件夹assets -> fonts Copy your fonts into fonts folder.将您的字体复制到字体文件夹中。

Use property app : font_name = "font_name_string" to apply font on view.使用属性app : font_name = "font_name_string"在视图上应用字体。

Example例子

   <!--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" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM