純粹的談?wù)刟ndroid.R.id.content

我們在Activity.onCreate中執(zhí)行setContentView,其實(shí)是往Window里面進(jìn)行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不存在,就創(chuàng)建一個DecorView,也就是執(zhí)行注解2
注解3:如果mContentParent不存在,就使用mDecor創(chuàng)建一個mContentParent,也就是執(zhí)行注解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 extends View> T findViewById(@IdRes int id) {
        return getDecorView().findViewById(id);//1
    }

注解1:getDecorView是從DecorView中獲取android.R.id.content

總結(jié),android.R.id.content來自DecorView,但是這個僅僅是DecorView的一個子View。
這里了解到它是子View之后,很多事情就需要注意了,例如title的去除等等

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容