Android中Window添加View的底层原理

2019-12-10 18:54:25刘景俊

public Window makeNewWindow(Context context) { 
    return new PhoneWindow(context); 
  } 

到此Window创建完成。
下面分析view是如何附属到window上的。看Activity的setContentView方法。

public void setContentView(int layoutResID) { 
    getWindow().setContentView(layoutResID); 
    initWindowDecorActionBar(); 
  } 

两部分,设置内容和设置ActionBar。window的具体实现是PhoneWindow,看它的setContent。

public void setContentView(int layoutResID) { 
    // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window 
    // decor, when theme attributes and the like are crystalized. Do not check the feature 
    // before this happens. 
    if (mContentParent == null) { 
      installDecor(); 
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) { 
      mContentParent.removeAllViews(); 
    } 
 
    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) { 
      final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID, 
          getContext()); 
      transitionTo(newScene); 
    } else { 
      mLayoutInflater.inflate(layoutResID, mContentParent); 
    } 
    final Callback cb = getCallback(); 
    if (cb != null && !isDestroyed()) { 
      cb.onContentChanged(); 
    } 
  }  

看到了吧,又是分析它。
这里分三步执行:
1.如果没有DecorView,在installDecor中的generateDecor()创建DecorView。之前就分析过,这次就不再分析它了。
2.将View添加到decorview中的mContentParent中。
3.回调Activity的onContentChanged接口。
经过以上操作,DecorView创建了,但还没有正式添加到Window中。在ActivityResumeActivity中首先会调用Activity的onResume,再调用Activity的makeVisible,makeVisible中真正添加view ,代码如下: