只要你使用過Activity,那麼你一定使用過setContentView這個方法。一般都是這樣調用該方法:
setContentView(R.layout.main);
然後,在手機或者模擬器上就可以看見自己的布局。
如果,你留意的話,setContentView還有很多過載方法:
public void setContentView(int layoutResID) { getWindow().setContentView(layoutResID); } public void setContentView(View view) { getWindow().setContentView(view); } public void setContentView(View view, ViewGroup.LayoutParams params) { getWindow().setContentView(view, params); }
那麼,getWindow()方法是做什麼的呢?一探究竟:
public Window getWindow() { return mWindow;}
可以看出,該方法返回一個Window執行個體。但是Window是一個抽象類別啊,怎麼可以有執行個體對象???
為瞭解決這個問題,可以看看Window類的說明:
Class OverviewAbstract base class for a top-level window look and behavior policy. An instance of this class should be used as the top-level view added to the window manager. It provides standard UI policies such as a background, title area, default key processing, etc.The only existing implementation of this abstract class is android.policy.PhoneWindow, which you should instantiate when needing a Window. Eventually that class will be refactored and a factory method added for creating Window instances without knowing about a particular implementation.
原來,Window類有一個子類PhoneWindow,那麼如何得知getWindow返回的是PhoneWindow執行個體呢?來,看下面這張圖:
如果,有興趣的話,您可以參照源碼看看。關於PhoneWindow這個類在下載的sdk的api中沒有說明。
至此,您應該明白setContentView()方法是調用PhoneWindow類的同名方法。源碼如下:
@Override public void setContentView(int layoutResID) { if (mContentParent == null) { installDecor(); } else { mContentParent.removeAllViews(); } mLayoutInflater.inflate(layoutResID, mContentParent); final Callback cb = getCallback(); if (cb != null) { cb.onContentChanged(); } } @Override public void setContentView(View view) { setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); } @Override public void setContentView(View view, ViewGroup.LayoutParams params) { if (mContentParent == null) { installDecor(); } else { mContentParent.removeAllViews(); } mContentParent.addView(view, params); final Callback cb = getCallback(); if (cb != null) { cb.onContentChanged(); } }
更多源碼,參看android源碼。
每個Activity都會執行個體化一個Window並且只有一個,而View就像是貼在Window上的裝飾品。窗戶(Window)只有一個,但是窗花(View)可以有很多。
關於PhoneWindow的其它內容,可以看看LayoutInflater基礎。