As the documentation states:
Android O lets you bundle fonts as resources by adding the font file in the res/font/ folder.
As a result:
You can retrieve fonts by using the
getFont(int)
method, where you need to pass the resource identifier of the font that you want to retrieve. This method returns a Typeface object. This encodes the first of the weight or style variants of your font, if it is a font family. You can then use the Typeface.create(typeface, style) method to retrieve specific styles.Note: The TextView already does this for you.
Typeface typeface = getResources().getFont(R.font.myfont); textView.setTypeface(typeface);
Unfortunately when I am using the above code I get the following error:
cannot resolve method 'getFont(?)'
Previously I used to do the following:
Typeface typeface = Typeface.createFromAsset(getAssets(), "fonts/myfont.ttf");
But now when I try to create the fonts folder inside assets folder, it automatically jumps inside res folder.
I am using android studio 2.3. Thanks in advance for any help.
Use this method from support library 26.
ResourcesCompat.getFont(context, R.font.your_font);
Source: https://developer.android.com/reference/android/support/v4/content/res/ResourcesCompat.html
I know this might be late but here's the documentation for using downloaded fonts with API versions before 26 (compatibility mode).
Basically, you have to define the font description as shown below (using both attributes - app and android) then use the ResourceCompat
class to access your font programmatically:
Typeface typeface = ResourcesCompat.getFont(context, R.font.myfont);
<?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/myfont-Regular"
app:fontStyle="normal" app:fontWeight="400"
app:font="@font/myfont-Regular"/>
<font android:fontStyle="italic" android:fontWeight="400"
android:font="@font/myfont-Italic"
app:fontStyle="italic" app:fontWeight="400"
app:font="@font/myfont-Italic" />
</font-family>
Cheers!
Try something like this
Typeface yourFont = Typeface.createFromAsset(getAssets(), "fonts/yourFont.ttf");
I haven't use it yet however as far as I know you can target Android O device only if you update your Android Studio to 2.4. And you need to update your SDK to latest build as well. Because as doc says getFont() available in Android O.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With