2013-04-26 50 views
3

为什么在onPause或onStop中调用findViewById(android.R.id.content).getRootView()会返回NPE,但在我在onCreate中调用它时不会返回?findViewById(android.R.id.content).getRootView()nullPointerException

+1

我最好的猜测 - 在onPause和onStop你没有从持有你的窗口中连接。 – 2013-04-26 20:59:30

+0

试试这两个链接:http://stackoverflow.com/questions/4486034/get-root-view-from-current-activity http://stackoverflow.com/questions/7776768/android-what-is-android-r -id-内容使用的换 – 2013-04-26 21:05:54

回答

1

这里是android.view.View.getRootView()的代码:

public View getRootView() { 
     if (mAttachInfo != null) { 
      final View v = mAttachInfo.mRootView; 
      if (v != null) { 
       return v; 
      } 
     } 

     View parent = this; 

     while (parent.mParent != null && parent.mParent instanceof View) { 
      parent = (View) parent.mParent; 
     } 

     return parent; 
    } 

它至少返回视图本身。

我试图登录findViewById(android.R.id.content)后,和findViewById(android.R.id.content).getRootView()的onStop的onPause的onCreate的onResume,它的工作一切正常。没有NPE。

你可以把你的活动代码?

0

我无法在Android 4.2.2上重现此错误。你可能会从其他东西获得NullPointerException。 顺便说一下,findViewById(android.R.id.content)返回rootview因此getRootView()通常是无效的。

相关问题