findViewById(R.id.xxx)返回Null

这里写图片描述

其中,R.id.textview 是layout2中的控件,当前MainActivity未引用过activity2。


当执行的时候,会报以下错误
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.widget.TextView.setText(java.lang.CharSequence)’ on a null object reference


在stackoverflow的相似问题中找到以下的解释

NotMainActivity calls setContentView with R.layout.activity_main as parameter that contains aViewPager and not a ListView. Since you don’t have a ListView declare in to that layout,findViewById(android.R.id.list) returns null, and when you try access it (callingsetAdapter) the NullPointerException is thrown.

可见原因是无法从当前的contentView中找到该控件以至于报空指针错误。

所以若要引用该控件,要到setContentView(R.layout.layout2)的Activity中引用

猜你喜欢

转载自blog.csdn.net/yyyerica/article/details/51387977