源码中单例模式工具类

  1. public abstract class Singleton<T> {
  2. @UnsupportedAppUsage
  3. public Singleton() {
  4. }
  5. @UnsupportedAppUsage
  6. private T mInstance;
  7. protected abstract T create();
  8. @UnsupportedAppUsage
  9. public final T get() {
  10. synchronized (this) {
  11. if (mInstance == null) {
  12. mInstance = create();
  13. }
  14. return mInstance;
  15. }
  16. }
  17. }

LayoutInflater

LayoutInflater是abstract,实现类是PhoneLayoutInflater。 单例模式-LayoutInflater - 图1Activity -> PhoneWindow -> DecorView -> DefaultLayout -> ViewGroup: mContentParent -> 用户xml布局。
单例模式-LayoutInflater - 图2
LayoutInflater的核心是inflate方法,通过inflate方法把布局添加到mContentParent中,mContentParent就是上层的DecorView,也就是把布局添加到DecorView中,DecorView继承自FrameLayout,其实就是个ViewGroup。在Activity中调用onResume后,会将onCreate中的sestContentView布局加载到DecorView中,DecorView添加到WindowManager中,最终现实用户布局到手机屏幕上。

inflate()

inflate方法内部的重要方法:createViewFromTag,rInflate。
inflate方法做了哪些事情?

  1. 解析xml中的根标签;
  2. 如果根标签是merge,调用rInflate解析,然后将merge标签下的所有子View直接添加到根标签;
  3. 如果是普通xml元素,用createViewFromTag对元素解析;
  4. 调用rInflate解析temp根元素下所有子View,并且将这些子View添加到temp中;
  5. 返回解析到根视图。

createViewFromTag()

onCreateView:解析内置View,PhoneLayoutInflater复写了onCreateView。
createView:解析自定义View

rInflate()

通过DFS构造视图树,解析View时候就会递归调用rInflate方法,最后通过回溯把没个View添加到parent中。通过DFS和回溯完成整个视图树的构建。

WindowManagerGlobal

WindowManagerGlobal是个单例模式,同时也属于桥梁模式。WindowManagerGlobal是WindowManager与WindowManagerImpl的桥梁。

思考

为什么Activity调用onResume后才会现实布局?

Activity显示原理 Activity界面显示全解析