54

I have tried using Typeface.createFromAsset(getAssets(),"font/myfont.ttf"));

I know font directory should be in assets but in my case, I have an existing font resource directory so I thought asset manager will read from font resource directory but I was wrong. I am creating Typeface to set custom font for collapsingToolbarLayout.

I found this answer but it requires me to keep font in assets

sziraqui
  • 4,315
  • 3
  • 22
  • 36
  • 3
    I suggest you to follow [this very good tutorial](https://segunfamisa.com/posts/custom-fonts-with-android-support-library). More info [here](https://developer.android.com/guide/topics/ui/look-and-feel/fonts-in-xml.html) – Eselfar Feb 08 '18 at 14:43

2 Answers2

141

This worked

Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);

Found this in the tutorial link by @Eselfar

sziraqui
  • 4,315
  • 3
  • 22
  • 36
  • 1
    If @Eselfar already answered you question then why you are posting the extra solution,if question is asked from any other person so that is acceptable.Please don't do these things for getting extra point. – Amit raj Apr 26 '19 at 10:00
  • 6
    Firstly, when I posted this, I didn't know it would help so many people. Secondly, unanswered questions keep lying stale on SO so it's a good practice to tell the community what solved your problem and thus close your question. Finally, the link may break in future so posting the relevant line from a long article is always helpful and obviously not a means of scoring points. *This is a community not a competition*, so stop assuming things and do something to help people. – sziraqui Apr 28 '19 at 14:49
  • 6
    I think I have explained myself quite clearly even though I didn't need to. If you are not satisfied with it, you can raise a question on meta and the mods will tell whats the correct behaviour. But before that read community guidelines of QnA and tell them what guidline you think I am violating. Comment section isn't for word war. – sziraqui May 01 '19 at 05:43
34

If you want to create the TypeFace from a font stored in assets folder,

enter image description here

you don´t need to define the directory, just the name of the font:

Typeface typeface =  Typeface.createFromAsset(getAssets(),"app_font.ttf");

You can create the Typeface using the resource id of the font stored into the /font folder like this :

Typeface typeface = ResourcesCompat.getFont(this, R.font.app_font);

your font must be stored into the /font directory

enter image description here

Jorgesys
  • 114,263
  • 22
  • 306
  • 247