setContentView源码分析

setContentView 就从我们自己新建的一个Activity开始

public class ActivityTest extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

    }

}
                ↓
                ↓ setContentView(R.layout.activity_test);
                ↓
public class AppCompatActivity extends ... {

     public void setContentView(@LayoutRes int layoutResID) {
        this.getDelegate().setContentView(layoutResID);
     }


                ↓
                ↓ getDelegate().setContentView(layoutResID);先找getDelegate()
                ↓ getDelegate()也在AppCompatActivity 中
                ↓
 @NonNull
    public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
    }
}
                ↓
                ↓  getDelegate() = AppCompatDelegate.create(this, this);
                ↓
public abstract class AppCompatDelegate {
  public static AppCompatDelegate create(Activity activity, AppCompatCallback callback) {
        return new AppCompatDelegateImpl(activity, activity.getWindow(), callback);
    }   
}

所以最后调用的是  AppCompatDelegateImpl 中的  setContentView 方法:

class AppCompatDelegateImpl extends ...{

    public void setContentView(int resId) {
        this.ensureSubDecor();
        ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
        contentParent.removeAllViews();
        LayoutInflater.from(this.mContext).inflate(resId, contentParent);
        this.mOriginalWindowCallback.onContentChanged();
    }

}

  接着去看 ensureSubDecor 方法:

ensureSubDecor 

private void ensureSubDecor() {
        if (!this.mSubDecorInstalled) {
            this.mSubDecor = this.createSubDecor();//核心代码

           //省略其它代码。。。
        }

    }

createSubDecor 

 private ViewGroup createSubDecor() {
        TypedArray a = this.mContext.obtainStyledAttributes(styleable.AppCompatTheme);
        if (!a.hasValue(styleable.AppCompatTheme_windowActionBar)) {
            a.recycle();
            throw new IllegalStateException("You need to use a Theme.AppCompat theme (or descendant) with this activity.");
        } else {
             

            this.mIsFloating = a.getBoolean(styleable.AppCompatTheme_android_windowIsFloating, false);
            a.recycle();
            this.mWindow.getDecorView(); ---> 核心代码 1 创建DecirView
            LayoutInflater inflater = LayoutInflater.from(this.mContext);
            ViewGroup subDecor = null;
            if (!this.mWindowNoTitle) {
                if (this.mIsFloating) {
                    subDecor = (ViewGroup)inflater.inflate(layout.abc_dialog_title_material, (ViewGroup)null);
                    
                } else if (this.mHasActionBar) {
                    
                    subDecor = (ViewGroup)LayoutInflater.from((Context)themedContext).inflate(layout.abc_screen_toolbar, (ViewGroup)null); 
                    
                }
            } else {
                if (this.mOverlayActionMode) {
                    subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple_overlay_action_mode, (ViewGroup)null);
                } else {
                    subDecor = (ViewGroup)inflater.inflate(layout.abc_screen_simple, (ViewGroup)null);
                }

                //其它代码省略...
                
                
            }
            通过上面subDecor = inflate(布局文件)可以看出,subDecor 的布局文件是下面四种布局文件之一:
                  1  abc_dialog_title_material
                  2  abc_screen_toolbar
                  3  abc_screen_simple_overlay_action_mode
                  4  abc_screen_simple
            if (subDecor == null) {
                如果subDecor为空就抛出异常 
                throw new IllegalArgumentException("AppCompat does not support the current theme features: { windowActionBar: " + this.mHasActionBar + ", windowActionBarOverlay: " + this.mOverlayActionBar + ", android:windowIsFloating: " + this.mIsFloating + ", windowActionModeOverlay: " + this.mOverlayActionMode + ", windowNoTitle: " + this.mWindowNoTitle + " }");
            } else {
                if (this.mDecorContentParent == null) {
                    this.mTitleView = (TextView)subDecor.findViewById(id.title);
                }

                ViewUtils.makeOptionalFitsSystemWindows(subDecor);
                 // 上面说了 subDecor 是四个布局文件中的一个创建,
                 // 每个布局文件都有一action_bar_activity_content   
                ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content);
                ViewGroup windowContentView = (ViewGroup)this.mWindow.findViewById(16908290);
                if (windowContentView != null) {
                    while(windowContentView.getChildCount() > 0) {
                        View child = windowContentView.getChildAt(0);
                        windowContentView.removeViewAt(0);
                        contentView.addView(child);
                    }

                    windowContentView.setId(-1);
                    contentView.setId(16908290);---> 核心代码 2 contentView的id被设置成16908290
                    if (windowContentView instanceof FrameLayout) {
                        ((FrameLayout)windowContentView).setForeground((Drawable)null);
                    }
                }

                this.mWindow.setContentView(subDecor);---> 核心代码 3 把subDecor填到mWindow中
                contentView.setAttachListener(new OnAttachListener() {
                    public void onAttachedFromWindow() {
                    }

                    public void onDetachedFromWindow() {
                        AppCompatDelegateImpl.this.dismissPopups();
                    }
                });
                return subDecor;
            }
        }
    }

总结一下createSubDecor方法:

1 this.mWindow.getDecorView(); 创建Decorview,下面详细说明

2 加载 subDecor 是一个ViewGroup,加载完成以后进行:

        ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content);

        ViewGroup windowContentView =  (ViewGroup)this.mWindow.findViewById(16908290);

3  this.mWindow.setContentView(subDecor); 将subDecor设置到this.mWindow

下面分析这三步骤

先看 1 this.mWindow.getDecorView();  ,this.mWindow 这个是啥呢?看下面

 AppCompatDelegateImpl(Context context, Window window, AppCompatCallback callback) {
        ......

       mWindow 的初始化是在AppCompatDelegateImpl构造函数里
                ↓
       this.mWindow = window;

        .....
       
    }
        想要知道mWindow是啥就要找到AppCompatDelegateImpl(context,window,callback)这个
        构造函数初始化的时候传入的window是啥
        还记得最开始我们从setContentView点进来的代码么
        
                ↓
                ↓  
                ↓
*********************************************************************** 
public class ActivityTest extends AppCompatActivity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);

    }

}
                ↓
                ↓ setContentView(R.layout.activity_test);
                ↓
public class AppCompatActivity extends ... {

     public void setContentView(@LayoutRes int layoutResID) {
        this.getDelegate().setContentView(layoutResID);
     }


                ↓
                ↓ getDelegate().setContentView(layoutResID);先找getDelegate()
                ↓ getDelegate()也在AppCompatActivity 中
                ↓
 @NonNull
    public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
    }
}
                ↓
                ↓  getDelegate() = AppCompatDelegate.create(this, this);
                ↓
public abstract class AppCompatDelegate {
  public static AppCompatDelegate create(Activity activity, AppCompatCallback callback) {
        在这里初始化的,activity就是AppCompatActivity ,window就是activity.getWindow()
        return new AppCompatDelegateImpl(activity, activity.getWindow(), callback);
    }   
}
***************************************************************************************

window就是AppCompatActivity.getWindow(),但是AppCompatActivity中没有getWindow()方法,
getWindow()是在其父类Activity中实现
public class Activity extends ... ... {

       private Window mWindow;
        
      final void attach(Context context, ......) {
        attachBaseContext(context);

           

        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        
        ......
       }

      public @Nullable Window getWindow() {
            return mWindow;
       }
}



最后找到window就是PhoneWindow对象。

接着我们就到PhoneWindow中查看关键的this.mWindow.getDecorView();

1 this.mWindow.getDecorView();

 @Override
    public final View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();  --->  核心代码
        }
        return mDecor;
    }

 private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1); --->  核心代码
           
            ....省略其它代码....
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor); --->  核心代码
            
            ....省略其它代码.....
            }
}

首先来看  mDecor = generateDecor(-1); generateDecor方法很简单就是创建了一个DecorView对象并返回赋值给 mDecor

 protected DecorView generateDecor(int featureId) {
      
        ...其它代码省略...        

        return new DecorView(context, featureId, this, getAttributes());
    }

接着看 mContentParent = generateLayout(mDecor); 

1:mContentParent是一个ViewGroup;

2 :generateLayout(mDecor);将上面刚刚创建的DecorView作为参数传了进去

protected ViewGroup generateLayout(DecorView decor) {
        
        ...其它代码省略...

        // Inflate the window decor.

        这里精简保留的,layoutResource = R.layout.布局文件 
        if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
            layoutResource = R.layout.screen_swipe_dismiss;
            
        } else if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
            if (mIsFloating) {
              
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_title_icons;
            }
            
        } else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
                && (features & (1 << FEATURE_ACTION_BAR)) == 0) {
            
            layoutResource = R.layout.screen_progress;
           
        } else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
           
            if (mIsFloating) {
               
                layoutResource = res.resourceId;
            } else {
                layoutResource = R.layout.screen_custom_title;
            }
           
        } else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
             
            if (mIsFloating) {
              
                layoutResource = res.resourceId;
            } else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
                layoutResource = a.getResourceId(
                        R.styleable.Window_windowActionBarFullscreenDecorLayout,
                        R.layout.screen_action_bar);
            } else {
                layoutResource = R.layout.screen_title;
            }
            
        } else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
            layoutResource = R.layout.screen_simple_overlay_action_mode;
        } else {
             
            layoutResource = R.layout.screen_simple;
            
        }

        mDecor.startChanging();
        layoutResource就是上面布局文件之中的一个,加载到mDecor即DecorView中
        ↓
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
       
        而上面布局文件中它们都有一个id是content的
        而且这个findViewById是在PhoneWindow直接使用?它是Activity?文章最后分析
        ↓
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        if (contentParent == null) {
            throw new RuntimeException("Window couldn't find content container view");
        }

        
        return contentParent; ← 返回DecorView的布局文件中id为content的控件
    }

总结一下generateLayout(mDecor)方法,就是将一个布局文件加载到DecorView中,并将布局中的id为content的控件返回赋值给mContentParent。这样PhoneWindow就新建了DecorView对象,并为其加载了布局文件,并将布局文件的content容器准备好。

到这里 1 this.mWindow.getDecorView() 就完成了。

2 就是准备好加载我们自己创建的布局文件的容器

    ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content);

    ViewGroup windowContentView =  (ViewGroup)this.mWindow.findViewById(16908290);

     windowContentView.setId(-1);

     contentView.setId(16908290); //其实这个就是加载我们自己创建的Activity的布局文件的容器

接着我们就来看看3 this.mWindow.setContentView(subDecor);同样是this.mWindow我们就到PhoneWindow中找setContentView方法

3 this.mWindow.setContentView(subDecor)

@Override
    public void setContentView(View view) {
        setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        // 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)) {
            view.setLayoutParams(params);
            final Scene newScene = new Scene(mContentParent, view);
            transitionTo(newScene);
        } else {
            核心方法
            ↓  
            mContentParent.addView(view, params);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

 mContentParent.addView(view, params);  

|--- mContentParent 就是上面DecorView中加载布局文件的 content 控件

|--- view 就是我们传递进来的subDecor

将subDecor加载到DecorView 布局文件的 content 控件中。还记得subDecor布局文件中 action_bar_activity_content 么:

ContentFrameLayout contentView = (ContentFrameLayout)subDecor.findViewById(id.action_bar_activity_content);

contentView.setId(16908290);
                

再来看最开始的setContentView

 public void setContentView(int resId) {
        this.ensureSubDecor();
        ViewGroup contentParent = (ViewGroup)this.mSubDecor.findViewById(16908290);
        contentParent.removeAllViews();
        LayoutInflater.from(this.mContext).inflate(resId, contentParent);
        this.mOriginalWindowCallback.onContentChanged();
    }

我们自己的布局文件被加载到了subDecor布局中id为 action_bar_activity_content的 ContentFrameLayout中。

而subDecor被加载到了DecorView布局中id为content的FrameLayout中;

DecorView是由PhoneWindow 创建

PhoneWindow 在Activity attach方法中初始化。

这样整个加载过程就串起来了。

是时候放上这样一张图了

DecorView加载的xml文件为下面中的一个:

screen_swipe_dismiss 

screen_title_icons 

screen_progress

screen_custom_title

screen_action_bar

screen_title

screen_simple_overlay_action_mode

screen_simple

而他们都有一个id为content的FrameLayout控件用来加载subDcor.

subDcor加载的xml文件为下面中的一个:

abc_dialog_title_material
abc_screen_toolbar
abc_screen_simple_overlay_action_mode
abc_screen_simple

而他们都有一个id为action_bar_activity_content 的 ContentFrameLayout 控件用来加载我们自定义的布局文件,就是我们创建Activity时候创建的xml文件。

上面还有一个问题PhoneWindow为啥可以直接findViewById? 点进去就会发现是在其父类Window中实现的

public abstract class Window {
     @Nullable
    public <T extends View> T findViewById(@IdRes int id) {
        return getDecorView().findViewById(id);
    }

    public abstract View getDecorView();

}

getDecorView的具体实现又回到了PhoneWindow 中;

    @Override
    public final View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();
        }
        return mDecor;
    }

这个方法看起来是不是很熟悉,就是我们初始化DecorView对象的方法,返回的就是我们初始化并加载了布局的DecorView.

所以PhoneWindow进行findViewById其实就是对其持有的DecorView进行操作。

猜你喜欢

转载自blog.csdn.net/u011288271/article/details/110517719