重溫View繪製原理(一)

1. View的知識前提

View的繪製是從上往下一層層迭代下來的:DecorView-->ViewGroup(--->ViewGroup)-->View,因此,在學習view的繪製原理前,咱們來先看看DecorView。android

1.1 DecorView的視圖結構

DecorView的視圖結構.jpg

Android 中 Activity 是做爲應用程序的載體存在,表明着一個完整的用戶界面,提供了一個窗口來繪製各類視圖。每一個activity都對應一個窗口window,這個窗口是PhoneWindow的實例,PhoneWindow對應的佈局是DecirView,是一個FrameLayout,DecorView內部又分爲兩部分,一部分是ActionBar,另外一部分是ContentParent,即activity在setContentView對應的佈局。bash

1.2 從源碼看DecorView

activity在啓動的時候都會在onCreate中執行setContentView方法:app

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
複製代碼

以setContentView爲切入點,分析Activity、PhoneWindow、DecorView、ActionBar和ContentParent的關係。ide

進入setContentView佈局

/**
     * Set the activity content from a layout resource.  The resource will be
     * inflated, adding all top-level views to the activity.
     *
     * @param layoutResID Resource ID to be inflated.
     *
     * @see #setContentView(android.view.View)
     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
複製代碼

進入activity的setContentView,發現裏面調用的是getWindow()的setContentView(layoutResID)。post

繼續看getWindow()學習

/**
     * Retrieve the current {@link android.view.Window} for the activity.
     * This can be used to directly access parts of the Window API that
     * are not available through Activity/Screen.
     *
     * @return Window The current window, or null if the activity is not
     *         visual.
     */
    public Window getWindow() {
        return mWindow;
    }
複製代碼
final void attach(...這裏省略代碼) {
        attachBaseContext(context);

        mFragments.attachHost(null /*parent*/);

        mWindow = new PhoneWindow(this, window, activityConfigCallback);
        mWindow.setWindowControllerCallback(this);
        ...這裏省略代碼
    }
複製代碼

從上面的源碼能夠看出setContentView裏面的是getWindow()實際上是PhoneWindow,這也正如前面所說的,每一個activity都對應一個窗口window,這個窗口是PhoneWindow的實例。ui

Activity-PhoneWindow.jpg

繼續,進入PhoneWindow裏面看看:this

// This is the top-level view of the window, containing the window decor.
    private DecorView mDecor;
複製代碼

PhoneWindow裏面有一個DecorView對象mDecor,再看看setContentView方法spa

@Override
    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();
        } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            mContentParent.removeAllViews();
        }

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                    getContext());
            transitionTo(newScene);
        } else {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }
複製代碼

首次進來mContentParent應該是null,進入installDecor()看看:

private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1);
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);

            .....此處省略代碼
        }
    }
複製代碼

在installDecor裏,mDecor=generateDecor(-1),再看看這個方法裏是怎麼生成DecorView的:

protected DecorView generateDecor(int featureId) {
        // System process doesn't have application context and in that case we need to directly use // the context we have. Otherwise we want the application context, so we don't cling to the
        // activity.
        Context context;
        if (mUseDecorContext) {
            Context applicationContext = getContext().getApplicationContext();
            if (applicationContext == null) {
                context = getContext();
            } else {
                context = new DecorContext(applicationContext, getContext());
                if (mTheme != -1) {
                    context.setTheme(mTheme);
                }
            }
        } else {
            context = getContext();
        }
        return new DecorView(context, featureId, this, getAttributes());
    }
複製代碼

裏面是直接new了一個DecorView。

看到這裏,PhoneWindow和DecorView的關係就一目瞭然了

PhoneWindow-DecorView.jpg

那問題來了,DecorView是如何跟ActionBar和ContentParent關聯起來的呢?

繼續回頭看源碼的installDecor()方法:

private void installDecor() {
        mForceDecorInstall = false;
        if (mDecor == null) {
            mDecor = generateDecor(-1);
            mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
            mDecor.setIsRootNamespace(true);
            if (!mInvalidatePanelMenuPosted && mInvalidatePanelMenuFeatures != 0) {
                mDecor.postOnAnimation(mInvalidatePanelMenuRunnable);
            }
        } else {
            mDecor.setWindow(this);
        }
        if (mContentParent == null) {
            mContentParent = generateLayout(mDecor);

            .....此處省略代碼
        }
    }
複製代碼

發現mContentParent是經過generateLayout(mDecor)生成的,那看看generateLayout方法:

protected ViewGroup generateLayout(DecorView decor) {
        // Apply data from current theme.

        TypedArray a = getWindowStyle();

        ...此處省略代碼

        int layoutResource;
        int features = getLocalFeatures();
        // System.out.println("Features: 0x" + Integer.toHexString(features));
        if ((features & (1 << FEATURE_SWIPE_TO_DISMISS)) != 0) {
            ...此處省略代碼
        } else {
            // Embedded, so no decoration is needed.
            layoutResource = R.layout.screen_simple;
            // System.out.println("Simple!");
        }

        mDecor.startChanging();
        mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);

        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
        ...此處省略代碼

        return contentParent;
    }
複製代碼
/**
     * The ID that the main layout in the XML layout file should have.
     */
    public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
複製代碼

generateLayout方法裏面根據不一樣的配置初始化的代碼特別多,我省略了一些其餘代碼

generateLayout方法裏面,mDecor加載了R.layout.screen_simple佈局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    android:orientation="vertical">
    <ViewStub android:id="@+id/action_mode_bar_stub"
              android:inflatedId="@+id/action_mode_bar"
              android:layout="@layout/action_mode_bar"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:theme="?attr/actionBarTheme" />
    <FrameLayout
         android:id="@android:id/content"
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:foregroundInsidePadding="false"
         android:foregroundGravity="fill_horizontal|top"
         android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>
複製代碼

能夠看到,R.layout.screen_simple是一個垂直的線性佈局,上面的ViewStub就是APP的appBar,下面的FrameLayout的id爲content!,activity所加載的xml頁面就是加載到這個佈局裏面

再看看mDecor.onResourcesLoaded(mLayoutInflater, layoutResource)這個方法

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
        ...此處省略代碼

        mDecorCaptionView = createDecorCaptionView(inflater);
        final View root = inflater.inflate(layoutResource, null);
        if (mDecorCaptionView != null) {
            if (mDecorCaptionView.getParent() == null) {
                addView(mDecorCaptionView,
                        new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
            }
            mDecorCaptionView.addView(root,
                    new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
        } else {

            // Put it below the color views.
            addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
        mContentRoot = (ViewGroup) root;
        initializeElevation();
    }
複製代碼

從上面的方法來看,root這個View所表明的的就是 R.layout.screen_simple,而後DecorView調用addView將root加載到DecorView裏面

奇怪了,只看到ContentParent初始化,沒看到ActionBar初始化啊?

再回頭看看Activity最開始的源碼:

/**
     * Set the activity content from a layout resource.  The resource will be
     * inflated, adding all top-level views to the activity.
     *
     * @param layoutResID Resource ID to be inflated.
     *
     * @see #setContentView(android.view.View)
     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
     */
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);
        initWindowDecorActionBar();
    }
複製代碼

原來ActionBar是在這裏初始化的,看看initWindowDecorActionBar():

/**
     * Creates a new ActionBar, locates the inflated ActionBarView,
     * initializes the ActionBar with the view, and sets mActionBar.
     */
    private void initWindowDecorActionBar() {
        Window window = getWindow();

        // Initializing the window decor can change window feature flags.
        // Make sure that we have the correct set before performing the test below.
        window.getDecorView();

        if (isChild() || !window.hasFeature(Window.FEATURE_ACTION_BAR) || mActionBar != null) {
            return;
        }

        mActionBar = new WindowDecorActionBar(this);
        mActionBar.setDefaultDisplayHomeAsUpEnabled(mEnableDefaultActionBarUp);

        mWindow.setDefaultIcon(mActivityInfo.getIconResource());
        mWindow.setDefaultLogo(mActivityInfo.getLogoResource());
    }
複製代碼
@RestrictTo({Scope.LIBRARY_GROUP})
    public WindowDecorActionBar(View layout) {
        assert layout.isInEditMode();

        this.init(layout);
    }
複製代碼
private void init(View decor) {
        this.mOverlayLayout = (ActionBarOverlayLayout)decor.findViewById(id.decor_content_parent);
        if (this.mOverlayLayout != null) {
            this.mOverlayLayout.setActionBarVisibilityCallback(this);
        }

        this.mDecorToolbar = this.getDecorToolbar(decor.findViewById(id.action_bar));
        this.mContextView = (ActionBarContextView)decor.findViewById(id.action_context_bar);
        this.mContainerView = (ActionBarContainer)decor.findViewById(id.action_bar_container);
        if (this.mDecorToolbar != null && this.mContextView != null && this.mContainerView != null) {
            this.mContext = this.mDecorToolbar.getContext();
            int current = this.mDecorToolbar.getDisplayOptions();
            boolean homeAsUp = (current & 4) != 0;
            if (homeAsUp) {
                this.mDisplayHomeAsUpSet = true;
            }

            ActionBarPolicy abp = ActionBarPolicy.get(this.mContext);
            this.setHomeButtonEnabled(abp.enableHomeButtonByDefault() || homeAsUp);
            this.setHasEmbeddedTabs(abp.hasEmbeddedTabs());
            TypedArray a = this.mContext.obtainStyledAttributes((AttributeSet)null, styleable.ActionBar, attr.actionBarStyle, 0);
            if (a.getBoolean(styleable.ActionBar_hideOnContentScroll, false)) {
                this.setHideOnContentScrollEnabled(true);
            }

            int elevation = a.getDimensionPixelSize(styleable.ActionBar_elevation, 0);
            if (elevation != 0) {
                this.setElevation((float)elevation);
            }

            a.recycle();
        } else {
            throw new IllegalStateException(this.getClass().getSimpleName() + " can only be used " + "with a compatible window decor layout");
        }
    }
複製代碼

ActionBar和ContentParent並不是是添加到DecorView上去的,而是自己就存在於DecorView,

對於有ActionBar的activity,DecorView的默認佈局是screen_action_bar.xml,裏面就會包含ActionBar和ContentParent 對於沒有ActionBar的Activity,會根據Activity所帶的參數選擇decorView的默認佈局,例如screen_simple.xml

選擇DecorView的默認佈局的相關的判斷邏輯是installDecor方法中調用generateLayout完成的.

看到這裏,DecorView和ContentParent、ActionBar的關係就一目瞭然了

DecorView-ContentParent-ActionBar.jpg

1.3 DecorView創建與viewRootImpl的聯繫

在ActivityThread的handleLaunchActivity中啓動Activity,當onCreate()方法執行完畢,上面所述的DecorView建立動做也完畢了,在handleLaunchActivity方法裏會繼續調用到ActivityThread的handleResumeActivity方法,看看這個方法的源碼:

@Override
    public void handleResumeActivity(IBinder token, boolean finalStateRequest, boolean isForward,
            String reason) {
        ...

        // TODO Push resumeArgs into the activity for consideration
        final ActivityClientRecord r = performResumeActivity(token, finalStateRequest, reason);
        ...

        if (r.window == null && !a.mFinished && willBeVisible) {
            r.window = r.activity.getWindow();
            View decor = r.window.getDecorView();
            decor.setVisibility(View.INVISIBLE);
            ViewManager wm = a.getWindowManager();
            WindowManager.LayoutParams l = r.window.getAttributes();
            a.mDecor = decor;
            l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
            l.softInputMode |= forwardBit;
            if (r.mPreserveWindow) {
                a.mWindowAdded = true;
                r.mPreserveWindow = false;
                // Normally the ViewRoot sets up callbacks with the Activity
                // in addView->ViewRootImpl#setView. If we are instead reusing
                // the decor view we have to notify the view root that the
                // callbacks may have changed.
                ViewRootImpl impl = decor.getViewRootImpl();
                if (impl != null) {
                    impl.notifyChildRebuilt();
                }
            }
            if (a.mVisibleFromClient) {
                if (!a.mWindowAdded) {
                    a.mWindowAdded = true;
                    wm.addView(decor, l);
                } else {
                    // The activity will get a callback for this {@link LayoutParams} change
                    // earlier. However, at that time the decor will not be set (this is set
                    // in this method), so no action will be taken. This call ensures the
                    // callback occurs with the decor set.
                    a.onWindowAttributesChanged(l);
                }
            }

            ...
    }
複製代碼

在handleResumeActivity方法中,獲取該activity所關聯的window對象,DecorView對象,以及windowManager對象,而WindowManager是抽象類,它的實現類是WindowManagerImpl,因此後面調用的是WindowManagerImpl的addView方法,看看源碼:

public final class WindowManagerImpl implements WindowManager {    
    private final WindowManagerGlobal mGlobal = WindowManagerGlobal.getInstance();
    ...
    @Override
    public void addView(View view, ViewGroup.LayoutParams params) {
        mGlobal.addView(view, params, mDisplay, mParentWindow);
    }
}

複製代碼

mGlobal則是WindowManagerGlobal的一個實例,那麼咱們接着看WindowManagerGlobal的addView方法:

public void addView(View view, ViewGroup.LayoutParams params,
            Display display, Window parentWindow) {
        ...

        ViewRootImpl root;
        View panelParentView = null;

        synchronized (mLock) {
            ...

            root = new ViewRootImpl(view.getContext(), display); // 1

            view.setLayoutParams(wparams);

            mViews.add(view);
            mRoots.add(root);
            mParams.add(wparams);
        }

        // do this last because it fires off messages to start doing things
        try {
            root.setView(view, wparams, panelParentView); // 2
        } catch (RuntimeException e) {
            // BadTokenException or InvalidDisplayException, clean up.
            synchronized (mLock) {
                final int index = findViewLocked(view, false);
                if (index >= 0) {
                    removeViewLocked(index, true);
                }
            }
            throw e;
        }
    }

複製代碼

在上面的方法中,實例化了ViewRootImpl類,而後調用ViewRootImpl#setView方法,並把DecorView做爲參數傳遞進去,在這個方法內部,會經過跨進程的方式向WMS(WindowManagerService)發起一個調用,從而將DecorView最終添加到Window上,在這個過程當中,ViewRootImpl、DecorView和WMS會彼此關聯,最後經過WMS調用ViewRootImpl#performTraverals方法開始View的測量、佈局、繪製流程。(參考:Android View源碼解讀:淺談DecorView與ViewRootImpl

DecorView的相關知識就記錄到這,下面開始view的繪製流程。

2. View的繪製流程

view繪製流程放在下一篇文章

相關文章
相關標籤/搜索