只要你使用过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);
- }
- public Window getWindow() {
- return mWindow;
- }
为了解决这个问题,可以看看Window类的说明:
- Class Overview
- Abstract 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.
如果,有兴趣的话,您可以参照源码看看。关于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();
- }
- }
每个Activity都会实例化一个Window并且只有一个,而View就像是贴在Window上的装饰品。窗户(Window)只有一个,但是窗花(View)可以有很多。