Search code examples
androidandroid-fontsandroid-typeface

Android Typeface createFromAsset


I Have a Custom View which draws text onto the Canvas. I want to change the font to a font stored in the assets folder.

I am using Android Studio so I created a folder src/main/assets and placed my ttf files in there.

Paint txt = new Paint()
Typeface font = Typeface.createFromAsset(getAssets(), "robotobold.ttf");
txt.setTypeface(font);

Problem is Android Studio doesn't recognize getAssets() inside my Custom View, however, it recognizes it inside my Activity. I have tried passing Typeface through from my Activity but when I do it it doesn't change the font.


Solution

  • You can use your View's getContext() method to get the current Context, then use it to get the assets:

    Typeface font = Typeface.createFromAsset(getContext().getAssets(), "robotobold.ttf");