NullPointerException when loading typeface from assets in Android Studio

淺唱寂寞╮ 提交于 2019-12-13 04:51:24

问题


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:

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:


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.



来源:https://stackoverflow.com/questions/25593572/nullpointerexception-when-loading-typeface-from-assets-in-android-studio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!