- Android и кастомные шрифты или «Да здравствует API 26»
- Как было раньше. Краткий обзор
- view.xml
- CustomFontTextView.class
- Но все изменилось в API 26
- Using Custom and Downloadable Fonts in Android
- The Older way of using Fonts
- Using Custom Font in Android
- Downloadable Fonts
- Custom and Downloadable Fonts on Android
- Version
- History: Difficulties in the Past
- Getting Started
- Requirements
- Add the latest support library
- Bundled fonts
- Creating a font family
- Custom fonts in layouts
- Custom fonts programatically
- Downloadable fonts
- How Font Providers work
- Security & certificates
- Downloadable fonts programatically
- Creating a font request
- Retrieving font information
- Downloadable fonts as XML resources
- Pre-declaring fonts in manifest
- Where To Go From Here?
Android и кастомные шрифты или «Да здравствует API 26»
Как было раньше. Краткий обзор
Если было много view где требовались нестандартные шрифты, то мы использовали что-то вроде такого:
view.xml
CustomFontTextView.class
И это я пропустил огромный кусок который отвечает за то, чтобы не писать каждый раз путь к шрифту, а указывать
Ну, или шли на гитхаб и в результате находили Calligraphy (7000 звезд!)
Ни для кого не секрет что этот подход содержал много минусов как в огромном количестве boilerplate кода, так и в том, чтобы сделать это эффективно и где-нибудь не утечь по памяти запрашивая каждый раз Typeface.
Но все изменилось в API 26
Похоже, гугл наконец-то сдался и решил отказаться от навязывания Roboto и сделал удобное подключение сторонних шрифтов, за что ему огромное спасибо.
Линк для тех, кто любит читать в оригинале.
Теперь подключение состоит всего из нескольких несложных шагов:
1. Создаем папку font в res
Resource type выбираем font
2. Перетаскиваем в новую папку все нужные нам в проекте шрифты
3. Создаем файл для семейства шрифтов.
Обратите внимание: я сразу добавил в пример то как должен выглядеть файл, если вы хотите поддерживать и более старые версии Андроида. (Начиная с 14). Если вам повезло и у вас таргет только на супер-новые девайсы, то ваш файл сократится в 2 раза
Ну а дальше остается только наслаждаться сборкой
Использование в TextView
Используем в стилях
И у вас больше не болит голова об эффективности 🙂
Источник
Using Custom and Downloadable Fonts in Android
At the Google I/O 2017, Android O or simple Android Oreo was launched and it came with a lot of cool features. One of the really interesting features for developers was the new way to apply fonts right in your XML files. Yeah, you heard it right. Now there is no need of writing some piece of code for using the fonts. Also, you can choose from any of the thousands of fonts on Google Fonts and use them in your app.
So, in this blog, you will understand how to use Custom and Downloadable Fonts in Android?
The Older way of using Fonts
Before we move forward to look for the new or the latest way of using the font, let’s revise the older way of using fonts. Before the release of Android O, fonts can be used in the following 2 ways :
- Using Typeface: One would typically need a custom view that extends the equivalent view were trying to apply a font to. In the custom view, one would create a Typeface and then call setTypeface (or a similar method, that, sets the typeface). One would also need to have the font file placed in the assets folder. The code in the custom view typically looks like:
- Calligraphy Library : You can use some existing libraries for various fonts used in Android. One of them is Calligraphy Library.
Using Custom Font in Android
To work with Custom Font, you need to install the latest version of Android Studio 3.x. This is important as some of the features are not supported on Android Studio 2.x — for example, the font resource directory. Once you are done with the installation of the latest version of Android Studio, create a project and add a text view in any of the activity(This is the text view on which we are going to apply custom font). Then follow the below steps :
- Add a font directory to your project: In the Android View, right click on the resfolder and go to New -> Android Resource Directory. Type fontas the name of the font and select fontas the resource type. Then click on Ok.
- Add the downloaded font to the font directory: Copy and Paste your font into res/font.I am using Pacifico font. You can get this font from FontSqirrel.
- Create a font-family XML file: You can create font families which contain a set of font files with their style and weight details. To create a new font family you need to create a new XML font resource. The benefit is that you can access it as a single unit instead of referencing individual font files for each style and weight. To create a font-family, right click on res/fontand choose New -> Font Resource File and give any name. In my case, I am using my_custom_font.xml.
Note: A really important thing to note is that we had to define attributes using both android and app namespaces. The app namespace is what ensures that the feature is backward compatible.
- Set the font in the XML: Now you can use the font-familyattribute to set the font in XML.
Below is the preview of the above code :
Downloadable Fonts
Now that we have seen how custom fonts work, let’s jump onto another novality — downloadable font . Android 8.0 (API level 26) and Android Support Library 26 introduce support for APIs to request fonts from a provider application instead of bundling files into APK or letting the APK download fonts. A font provider application retrieves fonts and caches them locally so that other apps can request and share fonts. How cool is that!
The feature is available on devices running Android API version 14 and higher through the Support Library 26.
Picture courtesy : Android Developer website
As you can see in the image above, apps using Downloadable Fonts make a FontRequest using the FontsContract API which retrieves the Typeface from the Font Provider. The Font Provider does not need to download fonts if it already exists in the Font Cache.
Benefits of downloadable fonts :
- Reduces the APK size
- Increase the app installation success rate
- Improves the overall system health as multiple APKs can share the same font through a provider. This saves users cellular data, phone memory, and disk space. In this model, the font is fetched over the network when needed.
In order to use the downloadable font in android studio, follow the below steps :
- If you want to use Android Studio to generate the required files, then you’ll need version 3.0+. Add the following (version 26+) to your module’s build.gradle:
- Select a text view in your app that you want to apply the font to and click on the fontFamily attribute under Attributes in the graphical layout
Select the “More Fonts…” at the bottom, which will open the dialog below.
- Make sure to have “ Create downloadable font” selected. This results in three files being downloaded — lato.xml, font_certs.xml and preloaded_fonts.xml.
This file contains the font attributes for loading a Typeface from the Google Fonts Provider Application.
The system uses these certificates to verify the font provider’s identity, to avoid getting fonts from an unknown source. If using the steps above, Android Studio should have automatically generated the string certificates for dev and prod in font_certs.xml below.
preloaded-fonts.xml
This file is referenced in the Android manifest which helps the framework pre-load fonts to avoid delays when the app is launched.
- Make sure this line is added to your app’s Manifest file, Android Studio should have done this automatically:
- Great, now you are ready to apply the fonts in XML!
All I had to do was set the font family in the app’s theme to get TextViews throughout the app to change to Lato, including parts that were bold or italicized. However, if you want to configure the weights, you can follow the same steps to get Lato Bold using Android Studio, and change the weight manually in lato_bold.xml that you can then apply in XML layouts:
That’s all about the custom and downloadable fonts in android. Hope you like the blog.
Источник
Custom and Downloadable Fonts on Android
See how to make great looking apps using the new custom and downloadable fonts capability available in Android Studio 3.0, all in Kotlin.
Version
- Kotlin 1.2, Android 4.4, Android Studio 3
Since the beginning of Android, there was no out of the box solution for using custom fonts. Only a small set of preinstalled fonts on the device was available.
You had to be creative and write a lot of code for such a trivial thing.
Recently, Google introduced Custom and Downloadable fonts for Android 8.0. They’ve also provided support for earlier Android versions through Support Library version 26.
In this tutorial, you’ll get to know how to use them by creating a simple quiz app. In the process, you’ll learn:
- How to add custom fonts in your app
- How to define font families
- How to add downloadable fonts from a provider
- How to retrieve font information
Let there be fonts! :]
History: Difficulties in the Past
Up until recently, to use a custom font on a View, you had to do several things:
- Put your font files in the assets folder
- Load the font from the asset file into a Typeface object
- Set that Typeface to your view using setTypeface()
The main disadvantage in this approach was that you couldn’t set the font in layout files – you had to do it in code:
To remedy that you could extend your view classes and add a custom attribute for passing the font file from layout. That was a little bit better but there were still issues:
- You had to extend every type of View you wanted to apply a custom font to
- On some devices loading from assets could take a long time so you had to cache fonts in memory
- In some cases things could get messy – for example if you had to change the font on Toolbar
Not to mention that it felt wrong extending a TextView just for setting a custom font.
Getting Started
Requirements
To work with custom fonts you’ll first have to install the latest Android Studio 3.x. This is important as some of the features are not supported on Android Studio 2.x – for example the font resource directory.
Install Android Studio by following the instructions in our Beginning Android development tutorial.
Your first task will be to switch to the latest support library. You can download the starter project here.
Open up Android Studio and import the starter project with File\Open. Select the location where you extracted the starter project and click Open on the dialog.
Once the project is open and synced, build and run the project.
You have a simple font quiz app. If you start the quiz you’ll get a series of 5 questions which ask you to guess the font of the text.
But wait – the text is always in the same (default) font! We’ll get to that shortly. First let’s add the latest support library.
Add the latest support library
Open build.gradle file in \app folder (in the Android project view you can find it under Gradle Scripts) and update the support library line in the dependencies < … >section:
This will add the latest version of the Android support library that ports Custom and Downloadable fonts back to Android from API versions 14 up.
You also need to change your compileSdkVersion and targetSdkVersion to 27. Finally, change the other support library dependencies (i.e., appcompat and design) to version 27.0.2.
Once done, click Sync now on the gradle notification on top of editor window.
After gradle has synced up, build and run the app again to make sure everything is still working:
There is no visible change for now, but hold tight – we are ready to add some custom fonts!
Bundled fonts
Google introduced a new feature with Android 8 – font resources. Put font files into the res\font folder to bundle them in the .apk as resources. These fonts compile in the R file and are available in Android Studio the same way as string, drawable and color resources.
The next thing you will do is add a custom .ttf font to the app. Download the OpenSans-regular font here.
Go back to Android Studio and make sure you select Android in Project navigator:
Click on the res folder, press ⌘N (or File\New) and select Directory.
A dialog to enter a new directory name will pop up. Name it font:
Now, right click on the new directory and click Reveal in Finder (macOS), Reveal in Explorer (Windows), or Show in Files (Linux). Move the downloaded OpenSans-Regular.ttf file to the fonts folder you’ve opened and rename it to opensans_regular.ttf. Only alphanumeric characters and underscore are valid in an android resource name.
Go back to Android Studio and open the res\layout\activity_main.xml file. Find AppCompatTextView with the id tvFontQuiz . Add the following property to it:
The layout code for the text view should look like this now:
Build and run your project.
You can see that the message is now in OpenSans font. Easy peasy!
Creating a font family
Another new capability is that you can create font families which contain a set of font files along with their style and weight details. To create a new font family you will actually create a new XML font resource. The benefit is that you can access it as a single unit instead of referencing individual font files for each style and weight as a separate resource.
You’ll now create a new font family. First, let’s get the bold version of OpenSans.
Repeat the same procedure from the last step and add new font file to the font folder of the project. Rename the file to opensans_bold.ttf.
The next thing you’ll do is create a font family resource.
Click on the res\font folder, press ⌘N (or File\New) and select Font resource file.
Type opensans under File name and click Ok.
Android studio will generate an empty font family resource:
Add two font files to the font family by using the element. It has three attributes:
- font: font file resource identifier
- fontStyle: style to which the font file corresponds, can be normal or italic
- fontWeight: text weight to use for the font
To add regular and italic font resource you’ll add two elements:
Note that to be backwards compatible to Android versions older than 8.0 you have to declare all font properties in the app namespace as well. This will use the custom font implementation from the support library. After adding them your resource file should look like this:
Now go back to res/layout/activity_main.xml and change the app:fontFamily property on tvMessage to opensans:
Build and run your project.
Custom fonts in layouts
You’ve already seen in previous steps how to add a custom font to TextView . Now you will add a custom font to a Theme, changing the default font on all Activities that use the Theme.
Open the file res/values/styles.xml.
Change app theme Theme.FontQuiz – add the fontFamily attribute:
Build and run the app.
You can see that across the app, OpenSans is now used:
Custom fonts programatically
You can set the custom font programatically as well. To do that you will use the ResourcesCompat class from the support library. Type the following at the end of the onCreate() method in MainActivity :
Build and run your project.
You can see that the font on the start button has been set to OpenSans Bold.
Note again that you use the support library to support Android versions earlier than Android 8.0.
Downloadable fonts
Now that you’ve seen how custom fonts work, let’s jump onto another novelty – downloadable fonts. Downloadable fonts allow you to add fonts to your application that download on demand or when your application starts.
This has more benefits:
- fonts get downloaded only when required
- reduced application .apk size
- more applications can share fonts through font providers which can reduce used disk space
How Font Providers work
Font providers take care of retrieving and caching downloadable fonts used across applications. This is what the process of requesting a font looks like:
All applications that use downloadable fonts pass their requests via FontsContractCompat . It then communicates with the requested font provider. A font provider is an application that takes care of fetching and caching the appropriate fonts. There can be more of them installed on a device but currently only a Google font provider is available.
Security & certificates
To ensure security when using font providers, you have to provide the certificate used to sign by the font provider. This enables Android to verify the identity of the font provider. You have to do this for font providers that are not pre-installed on the device or when using support library.
Your next task is to add the certificate for the Google font provider.
Click on the res\values folder, press ⌘N (or File\New) and select Values resource file.
In the dialog, name it font_certs and click Ok.
You define font provider certificates in a string-array . If the font provider has more than one set of certificates, then you must define an array of string arrays. The Google font provider used with the support library uses two sets of certificates, and the next step is to define an array for each set.
Add a string array in the new file by adding in the section and name it com_google_android_gms_fonts_certs_dev.
Add a single item to it with the following content:
Now add another string array with the name com_google_android_gms_fonts_certs_prod and add a single item to it with the following content:
Finally, create an array named com_google_android_gms_fonts_certs and add the two previously defined string arrays as its items.
Your font_certs.xml file should now look like this:
Build and run your project.
There is no visible change but you are now ready to add downloadable fonts.
Downloadable fonts programatically
The FontQuiz application is still missing one key feature – text in quiz questions always must be in font from the question.
You can implement requests to fetch downloadable fonts and apply them to a View in code as well. You must use the FontsContractCompat class from the support library to support Android versions older than 8.0.
Your task will be to use it to request and set a random font on the quiz question Activity .
Open QuestionActivity and find the showFont() method.
Font family names available for the quiz are in a list in res\values\family_names.xml file. The logic to pick a random font for the question and four offered answers is already there. Your job is to request and show the font with the name passed to showFont() .
First, hide all the buttons and show a ProgressView that will show hat font is loading by adding:
Build and run your project.
Click on “Start Quiz” and you’ll see disabled buttons and a progress indicator when the first question opens up:
Time to add the font request.
Creating a font request
Your next task is to add requesting downloadable fonts to QuestionActivity.
Create a query string and a request for the downloadable font:
When creating a FontRequest you have to pass:
- provider authority – only Google provider com.google.android.gms.fonts is available so far
- provider package – for Google font provider it’s com.google.android.gms
- query – query string that describes the font you are requesting
- array of certificates – to verify the provider
To request a new font use requestFont() method from FontsContractCompat . Add following to the end of showFont() :
Requesting a downloadable font is an asynchronous operation. Method requestFont() passes the result through a FontsContractCompat.FontRequestCallback interface. If the request is successful, FontContractorCompat calls onTypefaceRetreived() . Use the Typeface instance passed to set the font on a View. Enable all the buttons and hide progress indicator:
In case of an error, FontContractorCompat will call onTypefaceRequestFailed() . Use it to display an error message by calling showError() and passing it error code:
The last thing you need when requesting fonts is a Handler instance.
FontContractorCompat uses it to execute retrieving a font on a Thread associated with that Handler . Make sure you provide a Handler that is not associated with a UI thread.
For convenience, create a private field that will hold the handler and a property that will initialize and retrieve it:
Using the handlerThreadHandler property will initialize the handler on the first use and return it.
The call at the end of showFont() should now look like:
Build and run your project. Start the quiz:
Now you can see the text on each question in the appropriate font! :]
Retrieving font information
After you answer a question on the quiz, it would be cool to display a simple fact about the font in question. So your next task will be to retrieve information about a font family.
Go to loadFontFact() in QuestionActivity .
To get information about available fonts use fetchFonts() from FontsContractCompat . Like in the previous task, create a FontRequest first:
Then pass it to fetchFonts() :
This will return the information about the requested font family if there is one available with the given name. You’ll look it up in the fonts array of the object returned.
There are several properties for each font:
- uri – a URI associated to the font file by the font provider
- ttcIndex – If providing a TTC_INDEX file, the index to point to. Otherwise, 0.
- weight – font weight as an integer
- italic – boolean with value true if the font is italic style
Check that the status code of the result is ok and show the weight of the font to the user:
The string R.string.correct_answer_message is already prepared and takes one integer format param that represents the font weight.
Fetching font data is a blocking operation that should execute in the background. Use doAsync and uiThread blocks from Kotlin to execute it on a background thread:
Finally, add error handling and hide the progress indicator. The final code should in loadFontFact() look like:
Build and run your project. After answering a question you’ll see a fun fact about the font.
Downloadable fonts as XML resources
You can also define downloadable fonts as XML resources.
Right click on the res\font folder. Choose New\Font resource file. For the name type acme in the dialog.
Add font related attributes to the element:
All this looks familiar. Yes, that’s right – you are setting the attributes that you earlier passed to requestFont() . Only this time using XML.
Refer to the created font resource like you did with font family and .ttf files. Open res/activity_main.xml layout and set the acme font to tvFontQuiz textView:
Now repeat the process and add the font named Bilbo Swash Caps.
Open res/activity_main.xml and set the bilbo_swash_caps font on tvTheGreat textView:
Build and run your project:
You should see the FontQuiz labels in fonts now. When you first run the app you’ll notice that the font takes a little bit to load before showing because it’s not downloaded and cached yet.
Pre-declaring fonts in manifest
As a bonus – you can specify fonts that Android should preload before your app starts! To do this, you must specify them in the manifest.
Click on the res\values folder, press ⌘N (or File\New) and select Values resource file.
Name the file preloaded_fonts in the dialog.
Add an array of fonts with the resources tag and name it preloaded_fonts :
Open manifests\AndroidManifest.xml and add the following element inside tag:
Build and run your project:
Voila! Your fonts are now preloaded and ready to use once the app starts.
And, you have a nice Font Quiz app – it’s time to have fun! Can you score 5 / 5? :]
Where To Go From Here?
Here is the final project with all the code you’ve developed in this tutorial.
Now you know how to add custom and downloadable fonts in your application.
A great place to find more information is the official documentation from Google on
font resources, Fonts in XML and Downloadable fonts.
If you want to browse fonts that are available from the Google font provider check here.
If you have any questions or tips for other custom and downloadable font users, please join in the forum discussion below!
Источник