纯粹的谈谈android.R.id.content

我们在Activity.onCreate中执行setContentView,其实是往Window里面进行setContentView

//Activity.java
public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);//1
        initWindowDecorActionBar();
    }

注解1:getWindow()获取的是mWindow,而mWindow在attach的时候,初始化为PhoneWindow

//PhoneWindow.java
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();
        } ······
}

private void installDecor() {
        ······
        if (mDecor == null) {//1
            mDecor = generateDecor(-1);//2
            ······
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {//3
            mContentParent = generateLayout(mDecor);//4
            ······
        }
        ······
}

注解1:如果mDecor也就是DecorView不存在,就创建一个DecorView,也就是执行注解2
注解3:如果mContentParent不存在,就使用mDecor创建一个mContentParent,也就是执行注解4

protected ViewGroup generateLayout(DecorView decor) {
        ······
        int layoutResource;
        ······
        layoutResource = R.layout.****//1
        ······
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);//2
        
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);//3
        ······
        return contentParent;
}

注解1:layout就定义了content id
注解2:mDecor把资源文件addView到本身View中
注解3:Window.java中有定义变量ID_ANDROID_CONTENT = com.android.internal.R.id.content;
我们看findViewById

//Window.java
 public  T findViewById(@IdRes int id) {
        return getDecorView().findViewById(id);//1
    }

注解1:getDecorView是从DecorView中获取android.R.id.content

总结,android.R.id.content来自DecorView,但是这个仅仅是DecorView的一个子View。
这里了解到它是子View之后,很多事情就需要注意了,例如title的去除等等

你可能感兴趣的:(纯粹的谈谈android.R.id.content)