2013-04-26 51 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()通常是無效的。

相關問題