如果不使用setContentView(),则发生NullPointerException的原因 [英] Reason for NullPointerException if setContentView() is not used
问题描述
我知道我们需要在初始化任何视图之前将setContentView()
放在onCreate()
方法中,否则它将引发空指针异常.
但这是什么原因?setContentView()
与inflate()
方法相似吗?
I know that we need to place setContentView()
in the onCreate()
method before initializing any view otherwise it will throw a null pointer exception.
But what is the reason for it?Is the setContentView()
similar to the inflate()
method?
推荐答案
在初始化任何视图之前
before initializing any view
我不确定初始化任何视图"是什么意思.考虑到您剩下的问题,我将其解释为在活动中致电findViewById()
".
I do not know for certain what you mean by "initializing any view". Given the rest of your question, I am going to interpret this as meaning "call findViewById()
on the activity".
您需要先调用setContentView()
,然后再调用findViewById()
,因为否则将找不到小部件.
You need to call setContentView()
before calling findViewById()
, because otherwise there are no widgets to find.
setContentView()是否类似于inflate()方法?
Is the setContentView() similar to the inflate() method?
如果将布局资源ID传递给setContentView()
方法,则
setContentView()
将在其底下使用LayoutInflater
和inflate()
.
setContentView()
will use a LayoutInflater
and inflate()
under the covers, if you pass a layout resource ID into the setContentView()
method.
这篇关于如果不使用setContentView(),则发生NullPointerException的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!