NullPointerException when loading typeface from as

2019-09-07 12:02发布

I would like to use a custom typeface in my Android app. I followed instructions and created an assets folder in Android studio in which I put verdana.ttf, as shown on the picture:

assets

Then I call the following in my MainActivity activity:

public class MainActivity extends ActionBarActivity {

    Typeface mainFont = Typeface.createFromAsset(getAssets(), "verdana.ttf");

The code compiles, but when the activity is launched, I get a NullPointerException on the above line. I suspected the verdana.ttf file might be corrupted, but the error persists when trying different typefaces. Cleaning the project does not help either. Is the assets folder in the wrong location? What might I be doing wrong?

1条回答
Lonely孤独者°
2楼-- · 2019-09-07 12:51

You are trying to call createFromAsset() from an initializer. Please move this to onCreate(), after the super.onCreate() call. Methods you inherit in your Activity may not work before that point.

查看更多
登录 后发表回答