Как добавить шрифт в android studio

от admin

# Custom Fonts

Android O introduces a new feature, called Fonts in XML, which allows you to use fonts as resources. This means, that there is no need to bundle fonts as assets. Fonts are now compiled in an R file and are automatically available in the system as a resource.

In order to add a new font, you have to do the following:

  • Create a new resource directory: res/font .
  • Add your font files into this font folder. For example, by adding myfont.ttf , you will be able to use this font via R.font.myfont .

You can also create your own font family by adding the following XML file into the res/font directory:

You can use both the font file and the font family file in the same way:

Как добавить шрифт в android studio

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.
  • Step 2: Create the layout in the XML files.
  • Step 3: Now in the MainActivity(necessarily the Activity corresponding to the layout file where the TextView to be customised lies), set the typeface for that TextView.
  • Output:

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.
  • Output: />

Method 2

In this method we’ll create a separate java class dedicated 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:
  • Step 4: Complete the Java code by adding the required constructors.
  • Step 5: Create a method in the class wherein the typeface for the font is set.
  • Step 6: Call this method in each constructor. Refer to the following code for a better understanding.
  • Step 7: Now in your XML layout file, use this font class instead of the conventional TextView tag.
  • Output: />

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. The following files automatically get added to your project:
  • Step 7: Now the XML file will be look like:
  • Output:

Как добавить шрифт в android studio

enter image description here

enter image description here

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

enter image description here

  1. Добавьте зависимости в файл build.gradle:
  1. gradle-wrapper.properties :

enter image description here

  1. Создайте ресурсы папки в Project -> app (или имя вашего приложения) -> src -> main -> щелкните правой кнопкой мыши -> New -> Directory.
  2. Затем создайте новый каталог внутри ресурсов под названием «шрифты».
  • Создайте каталог ресурсов шрифта в папке res
  • Скопируйте и вставьте свой tff-файл в этот каталог
  • Затем используйте TextView в XML с помощью атрибута fontFamily.
  • Если описанные выше шаги не работают, вы можете создать FontFamily этого шрифта, используя этот ссылка

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.

Совет: Работаем со своими шрифтами в Android O

Jessica Thornsby

Jessica Thornsby Last updated Apr 19, 2017

Russian (Pусский) translation by Ellen Nelson (you can also view the original English article)

А вот и первая предварительная версия Android O!

В этой серии мы рассмотрим некоторые из современных функций пользовательского интерфейса, с которыми вы можете начать экспериментировать сегодня, в версии Android O для предварительного ознакомления разработчиками.

В первом совете я показал вам, как настроить свою разработку для поддержки этого раннего предварительного просмотра O, и как создать текст, который автоматически масштабируется в соответствии с текущей конфигурацией экрана. В этом совете мы увидим, как Android O сделает работу с пользовательскими шрифтами беззаботной.

Добавление ваших шрифтов в проект

Вы когда-нибудь хотели выделить отдельный фрагмент текста? Или, может быть, вы были убеждены, что ваш шрифт станет отличным способом добавить в ваше приложение дополнительную индивидуальность?

Хотя есть много преимуществ при использовании пользовательских шрифтов, работа с ними на Android традиционно была болезненным опытом, требуя, чтобы вы либо использовали библиотеку, либо создали пользовательский View .

К счастью, работа с пользовательскими шрифтами в Android будет намного проще, так как пользовательские шрифты станут полностью поддерживаемым типом ресурсов в Android O. Это означает, что добавление пользовательского шрифта в ваше приложение будет таким же простым, как добавление любого другого ресурса, например изображения и текста.

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

Android O поддерживает оба формата: .otf (OpenType) и .ttf (TrueType). Существует множество веб-сайтов, предлагающих такие шрифты бесплатно, поэтому потратьте несколько минут на поиск в Google, пока не найдете нужный шрифт.

Поскольку мы просто экспериментируем с новыми функциями Android O, не имеет особого значения, какой шрифт вы используете, но если вы ищете шрифты для использования в релизах вашего приложения, вы всегда должны смотреть условия использования этого шрифта. Только потому, что файл доступен для загрузки, не означает автоматически, что нет ограничений на то, как вы можете использовать и обращаться с этим файлом, поэтому всегда читайте мелкий текст!

Вы также должны задуматься о цели, содержании и целевой аудитории вашего приложения, так как разные шрифты передают разные сообщения. Если вы разрабатываете приложение, помогающее людям заполнять их налоговые декларации, то ваша аудитория с трудом сможет серьезно отнестись к финансовым и юридическим советам в вашем приложении, если оно поставляется со непонятным и странным шрифтом!

Как только вы найдете шрифт, с которым хотите работать, загрузите и разархивируйте его. На этом этапе вы должны проверить имя файла шрифта на наличие недопустимых символов — по сути это, что угодно, что не входит в строчные a-z, 0-9 или символ подчеркивания. Попробуйте использовать любые другие символы и Android Studio выдаст ошибку, как только вы попытаетесь сослаться на этот ресурс.

Так как у вас есть файл(ы) шрифтов, вам надо будет где-то их хранить:

  • Правый клик по папке app/res вашего проекта и выберите New > Android resource directory.
  • Откройте выпадающее меню и выберите font.
  • Введите font в File name.
  • Нажмите OK.

Переместите файлы вашего шрифта в новую папку res/font.

Использование своих шрифтов

Вы можете применить свой шрифт к тексту, используя новый XML атрибут android:fontFamily :

Test your custom font on your Android O AVD Test your custom font on your Android O AVD Test your custom font on your Android O AVD

Вы можете добавить пользовательский шрифт к любым стилям, которые вы создали в приложении.

Если вы хотите использовать свой шрифт программно, когда вы можете извлечь ваш шрифт используя метод getFont(int) , например:

Создание семейства шрифта

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

Если вы используете несколько версий одного и того же шрифта, вы можете сгруппировать их вместе в семейство шрифтов. Семейство шрифтов по существу является отдельным XML-файлом, в котором вы определяете каждую версию шрифта со всеми связанными с ним атрибутами стиля и веса.

Чтобы создать семейство шрифтов:

  • Убедитесь, что вы добавили все файлы шрифта в папку res/font вашего проекта.
  • Щелкните правой кнопкой мыши по папке res/font вашего проекта и выберите New > Font resource file.
  • Дайте этому файлу имя и нажмите OK.
  • Откройте этот XML-файл и определите все различные версии этого шрифта, а также их атрибуты стиля и веса, например:

Затем вы можете ссылаться на любой из шрифтов в этом семействе, используя атрибут android:fontFamily . Например:

Не забудьте протестировать!

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

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

Заключение

В этом совете я показала вам, как создать более стильный и уникальный текст, добавив пользовательские шрифты в свои проекты. В заключительном посте этой серии мы переведём наш фокус с текста на изображения, так как я покажу вам, как создавать адаптивные значки запуска, которые автоматически адаптируют свою форму в соответствии с текущим устройством.

В то же время ознакомьтесь с некоторыми из наших других руководств по разработке приложений для Android!

Похожие статьи