设置 TypeFace NullpointerException
Setting TypeFace NullpointerException
我想在我的 TextView
中添加一个 TypeFace
。这是我的 Java 代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
setContentView(R.layout.activity_help);
}
但是当我 运行 应用程序时,我收到一个 log cat 错误
Caused by: java.lang.NullPointerException
at com.example.enxin.crystallise.Help.onCreate(Help.java:15)
NullPointerException 有很多种,不知道怎么解决
//You have mistaken the order
setContentView(R.layout.activity_help);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
问题是您在设置内容视图之前调用 findViewById()
。
findViewById()
隐含地调用了 getWindow()
,此时它仍然是 null
。
在 初始化您的 View
:
之前调用 setContentView()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
}
我想在我的 TextView
中添加一个 TypeFace
。这是我的 Java 代码
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
setContentView(R.layout.activity_help);
}
但是当我 运行 应用程序时,我收到一个 log cat 错误
Caused by: java.lang.NullPointerException
at com.example.enxin.crystallise.Help.onCreate(Help.java:15)
NullPointerException 有很多种,不知道怎么解决
//You have mistaken the order
setContentView(R.layout.activity_help);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
问题是您在设置内容视图之前调用 findViewById()
。
findViewById()
隐含地调用了 getWindow()
,此时它仍然是 null
。
在 初始化您的 View
:
setContentView()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help);
TextView helptitle = (TextView)findViewById(R.id.title_help);
Typeface typeface = Typeface.createFromAsset(getAssets(), "beyond_the_mountains.ttf");
helptitle.setTypeface(typeface);
}