首先咱們從activity中的oncreate中的setContentView()方法介紹:
函數
在Window 抽象類中有三個setContentView的方法,Window類有是Activity的成員屬性
spa
PhoneWindow繼承了Window 實現了setContentView方法, 在PhoneWindow類中還有內部類DecorViewcode
DecorView繼承了Framelayout 是一個具體現實View容器。xml
在PhoneWindow中實現setContentView具體方法:
對象
(layoutResID) { (== ) { installDecor()} (!hasFeature()) { .removeAllViews()} (hasFeature()) { Scene newScene = Scene.(layoutResIDgetContext())transitionTo(newScene)} { .inflate(layoutResID)} Callback cb = getCallback()(cb != && !isDestroyed()) { cb.onContentChanged()} }
首先判斷了mContentparent 是否爲空,這個就是xml文件的根節點
繼承
mLayoutInflater.inflate(layoutResID, mContentParent);將咱們的資源文件經過LayoutInflater對象轉換爲View樹,而且添加至mContentParent視圖中(其中mLayoutInflater是在PhoneWindow的構造函數中獲得實例對象的LayoutInflater.from(context);
)。資源
再來看下PhoneWindow類的setContentView(View view)方法和setContentView(View view, ViewGroup.LayoutParams params)方法源碼:rem
(View viewViewGroup.LayoutParams params) { (== ) { installDecor()} (!hasFeature()) { .removeAllViews()} (hasFeature()) { view.setLayoutParams(params)Scene newScene = Scene(view)transitionTo(newScene)} { .addView(viewparams)} Callback cb = getCallback()(cb != && !isDestroyed()) { cb.onContentChanged()} }
直接分析setContentView(View view, ViewGroup.LayoutParams params)方法就行,能夠看見該方法與setContentView(int layoutResID)相似,只是少了LayoutInflater將xml文件解析裝換爲View而已,這裏直接使用View的addView方法追加道了當前mContentParent而已。
get
因此說在咱們的應用程序裏能夠屢次調用setContentView()來顯示界面,由於會removeAllViews。源碼
咱們先看一下源碼中LayoutInflater實例化獲取的方法
LayoutInflater (Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.)(LayoutInflater == ) { AssertionError()} LayoutInflater}
獲取LayoutInflater
實例的三種方式:
// 方式1
// 調用Activity的getLayoutInflater()
LayoutInflater inflater = getLayoutInflater();
// 方式2
LayoutInflater inflater = LayoutInflater.from(context);
// 方式3
LayoutInflater inflater = LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);