Как добавить шрифт в андроид студио
Перейти к содержимому

Как добавить шрифт в андроид студио

  • автор:

Android и кастомные шрифты или «Да здравствует API 26»

Если было много view где требовались нестандартные шрифты, то мы использовали что-то вроде такого:

view.xml
CustomFontTextView.class

И это я пропустил огромный кусок который отвечает за то, чтобы не писать каждый раз путь к шрифту, а указывать

Ну, или шли на гитхаб и в результате находили Calligraphy (7000 звезд!)

Ни для кого не секрет что этот подход содержал много минусов как в огромном количестве boilerplate кода, так и в том, чтобы сделать это эффективно и где-нибудь не утечь по памяти запрашивая каждый раз Typeface.

Но все изменилось в API 26

Похоже, гугл наконец-то сдался и решил отказаться от навязывания Roboto и сделал удобное подключение сторонних шрифтов, за что ему огромное спасибо.

Линк для тех, кто любит читать в оригинале.

Теперь подключение состоит всего из нескольких несложных шагов:

1. Создаем папку font в res
Resource type выбираем font

image

2. Перетаскиваем в новую папку все нужные нам в проекте шрифты

3. Создаем файл для семейства шрифтов.

Обратите внимание: я сразу добавил в пример то как должен выглядеть файл, если вы хотите поддерживать и более старые версии Андроида. (Начиная с 14). Если вам повезло и у вас таргет только на супер-новые девайсы, то ваш файл сократится в 2 раза

Using Custom Font as Resources in Android App

One of the really interesting features for developers android 8.0 (API level 26) introduces, Fonts in XML, which allows us to use fonts as resources. We can add the font file in the res/font/ folder to bundle fonts as resources. These fonts are compiled in R file and are automatically available in Android Studio.

To use the Fonts in XML feature on devices running Android 4.1 (API level 16) and higher, we have to use the Support Library 26. To add fonts as resources, perform the following steps in the Android Studio:

Image result for android custom font image banner

Create font directory

  • Right-click the res folder and go to New > Android resource directory. — The New Resource Directory window appears.
  • In the Resource type list, select font , and then click OK.
  • Note: The name of the resource directory must be font.

Add your font files in font folder

  • Add your ttf or otf fonts in font folder. The folder structure looks like below.

  • You may double-click a font file to preview the file’s fonts in the editor.

Create font family

To create a font family, perform the following steps in the Android Studio:

  • Right-click the font folder and go to New > Font resource file. The New Resource File window appears.
  • Enter the file name, and then click OK. The new font resource XML opens in the editor.
  • Enclose each font file, style, and weight attribute in the <font> element. The following XML illustrates adding font-related attributes in the font resource XML:

Use this Font

Now you can use this font in your app in below ways —

  • use the font directly in layout file
  • use the font programatically
  • use the font via style and app theme (this is the best way)

Use the font directly in layout file

  • In the layout XML file, set the fontFamily attribute to the font file you want to access.

Use the font programmatically

  • You may also set the font programmatically. To set the font programmatically follow the below codes.

Use the font via style and App theme

Open the styles.xml , and set the fontFamily attribute to the font file you want to access.

Download Google Fonts for your App

step 1: Select a text view in your app and click on the fontFamily attribute under Attributes in the graphical layout.

step 2: Select the “More Fonts…” at the bottom, which will open the dialog below. then you will see a new window will open, there you can type for your required and desired font from that list i.e) Regular, Bold, Italic etc.. as shown in below image.

step 4: Now there are two options:

Add font to project: fonts will be downloaded to your project in font folder( font folder will be auto generated if not created before). Now this font are ready to use. You can use this font by making font-family like before.

Create downloadable font: This is an another exciting feature of android app. Now i am not writing for this. You can see a nice article on Create downloadable font.

Thanks for reading this article. Don’t forget to give claps if your find this article helpful. Happy Coding:)

How to add Custom Fonts in Android

Google Fonts provide a wide variety of fonts that can be used to style the text in Android Studio. Appropriate fonts do not just enhance the user interface but they also signify and emphasize the purpose of the text. There are majorly three methods to add custom fonts to text in Android Studio. The first two methods involve the use of the Typeface class while the last method is quite direct and easy. Follow the entire article to explore all the methods.

Method 1

In this method, we’ll first download the font’s ttf file from the internet and then use them as an asset or a resource to set the Typeface. You may find the downloadable fonts here. Here Dancing Script font is used. Once you download the fonts of your choice, unzip the folder and copy the font file.

By creating a new Android resource directory:

    Step 1: In the project’s resource folder, create a new Android Resource Directory of Resource type: font and paste this ‘ttf’ file here. Note that while pasting it, keep in mind that a resource file’s name can consist of lower-case letters and underscores only, so refactor the file accordingly.

activity_main.xml

MainActivity.java

By creating a new asset folder:

  • Step 1: Create a new asset folder(app/New/Folder/Asset folder) in Android Studio and paste the ‘ttf’ file of the font here. The picture on the left shows how to add the assets folder to the project whereas the picture on the right shows the added ‘ttf’ file to it.
  • Step 2: While we keep the XML layout to be same as earlier, the Java code of the MainActivity is modified this way.

MainActivity.java

Method 2

In this method we’ll create a separate java class dediacted to a particular font and use this class instead of the conventional TextView tag in the XML file.

  • Step 1: Download the font of your choice and use either of the above two approaches to store it in the project. I have pasted my file in the assets folder.
  • Step 2: Create a new Java file in the package. Preferably name it according to the font that you want to implement. Here we have created a file named CalligraffittiRegular.
  • Step 3: Extend the following class in this Java file:

CalligraffittiRegular.java

activity_main.xml

Method 3

With Android 8.0 (API Level 26) a simpler method was introduced for using fonts as a resource in Android Studio. The android:fontFamily attribute of the TextView class is used to specify the font.

  • Step 1: Go to the XML file and go to the Design view.
  • Step 2: Click the TextView you want to change the font of.
  • Step 3: In the search bar, search for fontFamily.
  • Step 4: In the dropdown menu, you can check out the fonts available. In case you want to explore more, scroll down and click ‘More Fonts…‘.
  • Step 5: A dialog box pops up. Choose a font of your choice, choose the style you like in the preview, and click OK.
  • Step 6: This would create a downloadable font and add it automatically to your project.

How to import external font/ typeface in ANDROID STUDIO?

I want to know how do I use an external font in Android Studio as there is no Assets folder. I have look for a helpful turtorial on internet but they all pretend to use Assets folder.

I created an asset folder myself in src/main but Android Studio doesnt recognie getAssets() .

user avatar

7 Answers 7

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Go on your Project: app—>src—>main

Create a assets folder like this:

user avatar

If you have custom font then use following code:

Also place your font file in assets/fonts folder and follow the instructions from here.

NOTE: You have to make asset folder by yourself

user avatar

Put your font files (e.g customfont.tff and customfont_bold.tff) under the folder app>src>res>font> (Note: If it is not present, create font folder)

Additionally, create a file named fonts.xml inside the same folder with the following content:

Then, edit the file app>src>res>values>styles.xml to apply a default font for the entire app.

If you want to change the font of an individual UI element:

user avatar

To use external fonts, first download the font in .tff format Google font- Roboto

Add the font asset folder as shown in the image below

enter image description here

enter image description here

After the font asset folder is created, copy and paste the downloaded .tff font into the "font" folder. (make sure the name is formatted well. )

Reference the font in your theme.xml or any layout using the android:fontFamily="@font/splashfont" property.

This is how you do it in a theme.xml file

This is how you do it in a textview

user avatar

if you are having an error with «getAssets()» method then you can use following way. in assets folder puts font family

user avatar

If you’e tried both the res/asset/font and main/asset font folders and you’ve tried different fonts, and it failed to work — it’s likely to be an Android Studio bug.

I had the same problem but I solved it by importing my font to an online font editor (search for pentacom font editor) and exporting the font and saving it to a new ttf file. The resulting font will be lower in resolution but it worked for me.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *