如果不使用setContentView(),则发生NullPointerException的原因 [英] Reason for NullPointerException if setContentView() is not used

查看:107
本文介绍了如果不使用setContentView(),则发生NullPointerException的原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我们需要在初始化任何视图之前将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()将在其底下使用LayoutInflaterinflate().

setContentView() will use a LayoutInflater and inflate() under the covers, if you pass a layout resource ID into the setContentView() method.

这篇关于如果不使用setContentView(),则发生NullPointerException的原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆