With the advent of API 26, the time finally ended when we had to pervert and write custom View when the designer wanted to use something other than Roboto.
As it was before. Short review
If there was a lot of view where non-standard fonts were required, then we used something like this:
view.xml
<ru.my.app.with.CustomFontTextView android:id="@+id/title" ... app:my_typeface="proximaBold" />
CustomFontTextView.class
Typeface myCustomFontBold = Typeface.createFromAsset(getAssets(), "fonts/myCustomFont-Bold.otf"); setTypeface(myCustomFontBold);
And I missed this huge piece which is responsible for not writing the path to the font each time, but indicating
app:my_typeface="myCustomFontBold"
Well, or went to the githab and as a result found
Calligraphy (7000 stars!)
')
It is not a secret for anyone that this approach contained many drawbacks both in the huge amount of boilerplate code and in doing it efficiently and not leaking somewhere in memory requesting a Typeface each time.
But everything changed in API 26
It seems that Google finally gave up and decided to abandon the imposition of Roboto and made a convenient connection of third-party fonts, for which he thanks a lot.
Link for those who like to read in the original.
Now the connection consists of just a few simple steps:
1. Create a
font folder in
resResource type select
font
2. Drag and drop into the new folder all the fonts we need in the project
3. Create a file for the font family.
<?xml version="1.0" encoding="utf-8"?> <font-family xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <font android:fontStyle="normal" android:fontWeight="400" android:font="@font/lobster_regular" app:fontStyle="normal" app:fontWeight="400" app:font="@font/lobster_regular" /> <font android:fontStyle="normal" android:fontWeight="100" android:font="@font/lobster_light" app:fontStyle="normal" app:fontWeight="100" app:font="@font/lobster_light" /> </font-family>
Please note: I immediately added to the example how the file should look if you want to support older versions of Android. (Starting at 14). If you are lucky and you have a target only for super-new devices, then your file will be reduced by 2 times
Option for API> = 26lobster.xml <?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="normal" android:fontWeight="100" android:font="@font/lobster_light" /> </font-family>
Well, then it remains only to enjoy the build
Use in TextView <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:fontFamily="@font/lobster" />
Use in styles <style name="customfontstyle" parent="@android:style/TextAppearance.Small"> <item name="android:fontFamily">@font/lobster</item> </style>
And you no longer have a headache about efficiency :)