04.原始碼閱讀(setContentView-api26)

weixin_34353714發表於2018-03-27

關鍵詞:PhoneWindow DecorView

在呼叫setContentView方法設定佈局的時候,系統做了什麼?

在AppCompatActivity中

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

可以看到AppCompatDelegate中

public abstract void setContentView(@LayoutRes int resId);

是一個抽象方法
接下來看這個getDelegate是什麼

/**
     * @return The {@link AppCompatDelegate} being used by this Activity.
     */
    @NonNull
    public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
    }

AppCompatDelegate是一個類似工廠類的抽象類,會根據sdk版本create不同的子類

/**
     * Create a {@link android.support.v7.app.AppCompatDelegate} to use with {@code dialog}.
     *
     * @param callback An optional callback for AppCompat specific events
     */
    public static AppCompatDelegate create(Dialog dialog, AppCompatCallback callback) {
        return create(dialog.getContext(), dialog.getWindow(), callback);
    }

    private static AppCompatDelegate create(Context context, Window window,
            AppCompatCallback callback) {
        final int sdk = Build.VERSION.SDK_INT;
        if (BuildCompat.isAtLeastN()) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else if (sdk >= 23) {
            return new AppCompatDelegateImplV23(context, window, callback);
        } else if (sdk >= 14) {
            return new AppCompatDelegateImplV14(context, window, callback);
        } else if (sdk >= 11) {
            return new AppCompatDelegateImplV11(context, window, callback);
        } else {
            return new AppCompatDelegateImplV9(context, window, callback);
        }
    }

我們就是要從這些實現類中找到setContentView方法
從原始碼中可以看到這些子類的繼承關係

AppCompatDelegateImplN extends AppCompatDelegateImplV23
AppCompatDelegateImplV23 extends AppCompatDelegateImplV14
AppCompatDelegateImplV14 extends AppCompatDelegateImplV11
AppCompatDelegateImplV11 extends AppCompatDelegateImplV9
AppCompatDelegateImplV9 extends AppCompatDelegateImplBase
最終
AppCompatDelegateImplBase extends AppCompatDelegate

我們在AppCompatDelegateImplV9中找到setContentView方法

@Override
    public void setContentView(int resId) {
        //獲取到mSubDecor,這是一個ViewGroup,在這個ViewGroup中有一個id為content的ViewGroup,最終我們設定的layout就是新增到這個id為content的ViewGroup中的
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mOriginalWindowCallback.onContentChanged();
    }

這裡先簡單看一下LayoutInflator inflate的原始碼,以後會具體分析,看完這個我們再分析mSubDecor的獲取

LayoutInflater.from(mContext).inflate(resId, contentParent);

LayoutInflator中

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }
        //從一個layout的id中解析出XmlResourceParser
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");

            final Context inflaterContext = mContext;
            //獲取佈局的引數
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            //解析這個xml佈局
            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }
                //xml解析失敗,沒有找到start tag
                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();

                ......
                

                //merge標籤處理
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        ......
                        // 設定佈局引數
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {                   
                            temp.setLayoutParams(params);
                        }
                    }
                    ......
                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    ......
                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        //把view add到root中,inflate方法的作用其實就是把一個view新增到一個ViewGroup中
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            ......

            return result;
        }
    }

我們簡單看下rInflate和rInflateChildren方法

rInflate

/**
     * Recursive method used to descend down the xml hierarchy and instantiate
     * views, instantiate their children, and then call onFinishInflate().
     * <p>
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * override it.
     */
    void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {

        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {

            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();

            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                //新增到佈局中
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }
        //當佈局inflate完成的時候,回撥view的onFinishInflate方法,這個方法就是我們在自定義View時經常重寫的那個onFinishInflate方法,
        //在這個方法中為什麼獲取不到view的寬高?因為只是佈局inflate完成,還沒有進行測量,onMeasure還沒有開始
        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

rInflateChildren

/**
     * Recursive method used to inflate internal (non-root) children. This
     * method calls through to {@link #rInflate} using the parent context as
     * the inflation context.
     * <strong>Note:</strong> Default visibility so the BridgeInflater can
     * call it.
     */
    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        //最終呼叫的還是rInflate方法
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

看到這裡我們知道了一些東西,setContentView方法就是將我們設定的layout解析成view之後add到了mSubDecor的一個id為android.R.id.content的ViewGroup中(contentParent)了,然後再次回到setContentView 方法中的ensureSubDecor方法中,mSubDecor是什麼?如何獲取的?

private void ensureSubDecor() {
        if (!mSubDecorInstalled) {
            mSubDecor = createSubDecor();  
            .......
        }
    }
private ViewGroup createSubDecor() {
  
        ......

        // Now let's make sure that the Window has installed its decor by retrieving it
        mWindow.getDecorView();

        ......

        // Now set the Window's content view with the decor
        mWindow.setContentView(subDecor);

        ......

        return subDecor;
    }

這裡的Window指的是PhoneWindow

mWindow.getDecorView();

//如果mDecor不存在就建立,所以官方註釋說
Now let's make sure that the Window has installed its decor by retrieving it
@Override
    public final View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();
        }
        return mDecor;
    }

installDecor這個方法,我們關注兩個點,第一,它建立了DecorView,並返回,
第二,通過DecorView建立了mContentParent

private void installDecor() {
        mForceDecorInstall = false;
        
        if (mDecor == null) {
            //如果mDecor為null,就建立出來
            mDecor = generateDecor(-1);
            ......
        } else {
            //給DecorView設定Window
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            //如果mContentParent為null,就建立出來
            mContentParent = generateLayout(mDecor);
            ........
        }
    }
    //DecorView是被new出來的
    protected DecorView generateDecor(int featureId) {

        ......

        return new DecorView(context, featureId, this, getAttributes());
    }
    
    protected ViewGroup generateLayout(DecorView decor) {
        ......
        //The ID that the main layout in the XML layout file should have.這是一個系統層面的ViewGroup
        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        ......
        return contentParent;
    }

原始碼new出來了一個DecorView,然後再根據具體情況選取一個系統的佈局add到DecorView中,subDecor就是這個系統佈局,這個佈局會被新增到DecorView中,DecorView又是被新增到PhoneWindow上
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) {
            //確保mContentParent不為null,這裡基本上不存在為null的情況,因為在
            //mWindow.getDecorView();的時候如果為 null就會建立出來
            installDecor();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            ......
        } else {
            //把subDecor加入了mContentParent
            mContentParent.addView(view, params);
        }
        ......
    }

這樣一個過程下來,基本上setContentView的作用有了基本的結論
這裡借用一下一位博主的圖片來說明手機螢幕的View層級關係


7305851-f9dc9cc66ce36114.png
4314397-a952a39dd0bba2d9.png

相關文章