- Android и кастомные шрифты или «Да здравствует API 26»
- Как было раньше. Краткий обзор
- view.xml
- CustomFontTextView.class
- Но все изменилось в API 26
- How to Install Custom Fonts on Android Device? [Complete Guide]
- Android is open source
- 1. Android Launchers
- 2. iFont (Expert of Fonts)
- A word of caution:
- Here’s How to Download & Install Custom Fonts On Android Without Root
- How to Install Custom Fonts Typefaces on a Rooted Android Device?
- FontFix: This lets you install custom fonts easily.
- What are system fonts?
- How to edit /system/fonts directory- The Right Way.
- Hands-on example:
- Download and install ES File Explorer
- Now, let’s jump to the geeky part where you will be using the ADB commands to install fonts in android.
- Conclusion
- Using Custom and Downloadable Fonts in Android
- The Older way of using Fonts
- Using Custom Font in Android
- Downloadable Fonts
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
Используем в стилях
И у вас больше не болит голова об эффективности 🙂
Источник
How to Install Custom Fonts on Android Device? [Complete Guide]
Overview: In this article, you will learn to install custom fonts on the android device wheater it is rooted or not along with a complete installation guide.
Fonts are everything. The state of social media existence depends greatly upon the diversity of fonts available on the internet.
Like computers, smartphones are also enriched with many font typefaces. Though smartphone manufacturers fabricate a handful of well-known font types, you might, at some point in time, want to install fonts on Android that aren’t readily preinstalled.
This comprehensive guide will teach you exactly how to install otf / ttf fonts on Android. The custom fonts as you want.
Android is open source
Even those with some technical expertise would admit that Android’s love for open source makes tinkering a lot more fun as compared to iOS.
Android fonts aren’t by any means easy to install, but at the same time, they aren’t too hard. The concept is pretty simple which I’ll enumerate below.
To lift-off, let us take it easy and discuss some “unrooted” ways to install custom fonts on Android.
1. Android Launchers
Android launchers not only revamp your smartphone top-down they also give you many new fonts to use. The exact font typefaces vary according to font packs that are combined with these launchers.
- iPhone Launcher
- Go Launcher
- Microsoft Launcher
- Nova Launcher
Almost all Android launchers are available on Google Play Store and come with rolling ads. They can be removed by in-app upgrades. Doing so would also give you a lot of free themes, icon packs, and much more.
2. iFont (Expert of Fonts)
iFont contemplates users by delivering a rich set of font typefaces that are compatible with the Android system.
It has multi-lingual support which includes Arabic, Myanmar, Japanese, Korean, Japanese, French, Spanish, Vietnamese, Russian, among several others.
iFont is rewarding owning it but it comes with a downside which is that it might require a rooted Android device unless you own one of the followed enlisted version:
- Meizu
- Xiaomi (MiUi)
- Huawei (Emotion UI)
- Samsung Galaxy S7, S8, S9, Note, and Note II
If you own one of these supported devices, you can install ttf fonts on android without root. To download fonts on android pick a font, hit download, and start using it right away.
iFont does come with one limitation for devices that aren’t listed above. You might face some compatibility issue that asks you to root your device.
You should install TWRP Custom ROM on your Android device and then use either Magisk or SuperSu to root.
A word of caution:
Rooting cancels any outstanding warranty on the smartphone.
Rooting exposes your Android device to many vulnerabilities such as adware, spyware, malware, and other virtual threats.
Your phone could brick in many different ways, if you don’t stick to this guide. Don’t go out venturing into your own tactics.
Keep the tools readily available to perform rooting. There’s no alternative to that.
Last but not the least, make sure you back up all your files before rooting.
With that out in order, let us go to the next point and check the apps that support rooted smartphones.
Once rooted, you can download and use those font typefaces as well.
Here’s How to Download & Install Custom Fonts On Android Without Root
To download fonts on android, first of all, you need to download iFont, once you get this on your device-
- Browse through the list of fonts under Online.
- Then download the desired font and hit Set.
- When prompted for the font mode, select System mode, then tap OK.
- Reboot your device and enjoy the new font.
- To use a local .ttf font file, copy it from your PC and paste it inside the Android device /sdcard/ifont/custom directory.
Thereafter, perform the following steps in a sequence.
- Tap the Menu from the main screen.
- Then tap Settings, Change Font Mode.
- For rooted non-Samsung devices, choose System Mode. For Samsung devices, choose the Samsung mode.
- Hit the Custom tab, then pick the font you like then tap Set later.
- Press OK when the prompt shows up.
- Tap OK again at the prompt.
- Reboot your device after applying the new font.
How to Install Custom Fonts Typefaces on a Rooted Android Device?
Since your Android is now rooted, let us start off with something easy, shall we?
I promise you will forget ever having to put up with the same font again.
FontFix: This lets you install custom fonts easily.
FontFix is a goldmine of Android font typefaces.
Pick any font you like from the ‘preview’ then set it up system-wide.
FontFix is ad-supported. So. if you want to get rid of annoying ads you must shed a few bucks.
All font typefaces on FontFix also have a ‘.ttf’ as a suffix.
If there are Android custom fonts that you want to download, it is recommended that you first download them onto your PC and then move to the /sdcard directory of your device.
Don’t have a .ttf file? Follow these steps.
- Launch FontFix app.
- Go to Menu and choose Select to start backing up the default font.
- When prompted with SuperSu permissions, grant them.
- Locate the .ttf file that you saved earlier.
- Choose the .ttf file to start its installation from the pop-up (this will be set as a default font.)
- Grant SuperSU permissions.
- After the installation is finished, FontFix will require a reboot. Click Yes when prompted.
Instead of bringing over user-defined font typefaces, you can go through preconfigured font styles in the app.
The Server and Preview tabs are displayed from the Local tab in the Font Installer’s interface.
- Select the Server tab.
- Choose the font that you want to download and install.
- Wanna check a sample text written in your chosen font style, tap Preview.
- Finally, confirm your choice by tapping Install. It will install all of the Android font styles.
- Perform another Backup, and then reboot the device when it is ready.
If installed correctly, Android custom fonts will become a part of the system fonts.
Therefore, you need to know about the default system fonts.
What are system fonts?
System fonts come pre-installed from your OEM. Generally, Roboto is the default font.
This popular Sans Serif font pack has variations too.
- Roboto-Regular.tff
- Roboto-Bold.tff
- Roboto-Italic.tff
- Roboto-BoldItalic.tff
Where are fonts stored on Android?
System fonts reside inside the /system/fonts directory.
Before you begin tinkering with system files, you need to locate the .tff file for ROBOTO. Take caution since all changes are permanent.
How to edit /system/fonts directory- The Right Way.
All default system font files reside inside /system/fonts.
As a result, it’s best to use ADB commands.
Also, an efficient File Explorer with root access would be needed.
Hands-on example:
Let’s say you want to install custom font “Proxima-Nova“, gather its .tff file, and using ADB commands, replace Roboto-Regular.tff with Proxima-Nova.tff.
In order to not alter anything within the system, rename “Roboto-Regular.tff” to “Roboto-Regular1.tff“.
Bear in mind not to move this file out of this folder. Everything needs to be within /system/fonts directory.
Create a complete backup of the system at this point.
Since you already have TWRP installed as your Custom ROM, create a NANDroid backup of the system at this point before proceeding any further.
Should anything go awry, you can easily restore everything back to as it was.
Download and install ES File Explorer
Using the ES File Explorer is relatively easier than using the ADB commands. Follow these steps exactly as indicated:
- Launch the application.
- Transfer the renamed file “Roboto-Regular(1).tff” to the /sdcard directory.
- Tap Menu, Settings, Root Settings.
- Open the Root Explorer and grant SuperSU/Magisk permissions.
- Remember to enable “mount file system” feature.
- Locate /system/fonts directory and rename Roboto-Regular.tff
- Navigate to the desired font file & rename it to Roboto-Regular.tff
- Copy this file to /system/fonts, then select OK.
- Open /system/fonts directory and access properties of the custom font.
- Tap “Change” to set Read & Write permission for the User, then tap OK.
- Save changes and hit Reboot device.
So far, you were able to get away without actually using any of the commands.
Now, let’s jump to the geeky part where you will be using the ADB commands to install fonts in android.
Before using the ADB commands, ensure that you have the following:
- A rooted Android device with root access.
- Android Software Development Kit (SDK) installed and setup.
- Device’s USB drivers for Windows PC.
- Verify that the ADB is able to detect your device.
- A USB cable, preferably that came with your device.
- Replacement font files that you want to use.
- Open a Command Prompt or PowerShell with admin privileges.
- Right-click then select Run as Administrator.
Lastly, enter the following set of commands.
Now, on your PC you will perform the following steps.
- Rename Proxima-Nova.tff to Roboto-Regular.tff
- Copy and paste or move the renamed “Proxima Nova” font to the /sd card.
- Open Command Prompt on PC.
Run the following set of commands on the terminal to append changes to your device instantly.
Thereafter, reboot your device normally and verify if the system displays a new font.
Apart from iFont there are some other Android font installer is available one of them is by UpToDown, download font installer, choose the font you would like to install, and hit the install button. This installer works only on the rooted android device.
Conclusion
If you follow the above guide step by step you would be able to install fonts on an android Android device. The hesitation behind performing an Android root is understandable. But that means you are solely relying on Android Launchers.
As good as they come, they are not in the same class as Android custom fonts. With that said, if you do not consider yourself a techie, it would be best to not try these methods, otherwise, have fun Androiding!
Источник
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.
Источник