美文网首页
View的绘制流程三、DecorView的添加

View的绘制流程三、DecorView的添加

作者: b42f47238b43 | 来源:发表于2017-11-12 18:02 被阅读0次

通过之前的文章了解了setContentViewinflate方面的知识下面就可以正式开始讲解View的绘制流程了,而DecorView作为Activity的跟布局链接了整个View的绘制流程现在我们就来看看DecorView是怎样添加到Activity中的吧
我们从ActivityThreadhandleLaunchActivity()方法开始

private void handleLaunchActivity(ActivityClientRecord r, Intent customIntent, String reason) {
    // Make sure we are running with the most recent config.
    ...省略无关代码...
    //创建activity在该方法中会创建PhoneWindow并且调用activity的onCreat方法
    Activity a = performLaunchActivity(r, customIntent);
    if (a != null) {
        r.createdConfig = new Configuration(mConfiguration);
        reportSizeConfigurations(r);
        Bundle oldState = r.state;
        //调用handleResumeActivity()这个方法开始添加DecorView
        handleResumeActivity(r.token, false, r.isForward,
                !r.activity.mFinished && !r.startsNotResumed, r.lastProcessedSeq, reason);
        if (!r.activity.mFinished && r.startsNotResumed) {
            performPauseActivityIfNeeded(r, reason);
            if (r.isPreHoneycomb()) {
                r.state = oldState;
            }
        }
    } else {
        try {
            ActivityManagerNative.getDefault()
                    .finishActivity(r.token, Activity.RESULT_CANCELED, null,
                            Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
        } catch (RemoteException ex) {
            throw ex.rethrowFromSystemServer();
        }
    }
}

上述代码中我们主要关注两个点第一activity的创建方法performLaunchActivity该方法主要是创建activity创建Phonewindow并且调用activity的生命周期方法onCreate另外一个handleResumeActivity方法看方法名字我们就知道这个肯定和ActivityonResume方法有关

final void handleResumeActivity(IBinder token,
                                boolean clearHide, boolean isForward, boolean reallyResume, int seq, String reason) {
    ...
    if (r.window == null && !a.mFinished && willBeVisible) {
        //回调onResume方法
        r = performResumeActivity(token, clearHide, reason);
        r.window = r.activity.getWindow();
        //创建decorView
        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 && !a.mWindowAdded) {
            a.mWindowAdded = true;
            //添加DecorView到
            wm.addView(decor, l);
        }
    ...
}
    ...        
}

getDecorView方法在上篇博客中已经分析过了,这里我们主要分析addView()方法点进去会发现WindowManager是个接口并没有实现addView()方法,具体实现addView方法的是WindowManagerImpl

public void addView(@NonNull View view, @NonNull ViewGroup.LayoutParams params) {
    applyDefaultToken(params);
    mGlobal.addView(view, params, mContext.getDisplay(), mParentWindow);
}

继续追踪

public void addView(View view, ViewGroup.LayoutParams params,
        Display display, Window parentWindow) {
        ...
        //创建ViewRootImpl  这个很重要之后我们分析View的测量摆放绘制流程都是从这个方法开始的
        ViewRootImpl root;
        root = new ViewRootImpl(view.getContext(), display);
        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 {
        //将decorView添加到ViewRootImpl中
        root.setView(view, wparams, panelParentView);
    } catch (RuntimeException e) {
        // BadTokenException or InvalidDisplayException, clean up.
        synchronized (mLock) {
            final int index = findViewLocked(view, false);
            if (index >= 0) {
                removeViewLocked(index, true);
            }
        }
        throw e;
    }
}

跟踪root.setView(view, wparams, panelParentView);代码

public void setView(View view, WindowManager.LayoutParams attrs, View panelParentView) {
    synchronized (this) {
        if (mView == null) {
            mView = view;
            //发起绘制流程
            requestLayout();
            ...
            //设置ViewRootImpl为DecorView的父控件
            view.assignParent(this);
            ...
        }
    }
}

上述有两个很重要的代码第一个是requestLayout()方法,该方法 我们在开发过程中应该经常遇到,一般调用他进行View重绘,第二个view.assignParent(this);方法,设置DecorView的parent为ViewRootImpl。为什么要这样做呢我们来看一下ViewrequestLayout()方法是怎样调用的吧

public void requestLayout() {
    if (mMeasureCache != null) mMeasureCache.clear();
    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == null) {
        // Only trigger request-during-layout logic if this is the view requesting it,
        // not the views in its parent hierarchy
        ViewRootImpl viewRoot = getViewRootImpl();
        if (viewRoot != null && viewRoot.isInLayout()) {
            if (!viewRoot.requestLayoutDuringLayout(this)) {
                return;
            }
        }
        mAttachInfo.mViewRequestingLayout = this;
    }
    mPrivateFlags |= PFLAG_FORCE_LAYOUT;
    mPrivateFlags |= PFLAG_INVALIDATED;
    if (mParent != null && !mParent.isLayoutRequested()) {
        //调用parent的requestLayout方法
        mParent.requestLayout();
    }
    if (mAttachInfo != null && mAttachInfo.mViewRequestingLayout == this) {
        mAttachInfo.mViewRequestingLayout = null;
    }
}

ViewrequestLayout()会调用ParentrequestLayout()这样层级调用最终会调用到ViewRootImplreuqestLayout()方法,跟踪一下该方法

public void requestLayout() {
    if (!mHandlingLayoutInLayoutRequest) {
        checkThread();
        mLayoutRequested = true;
        scheduleTraversals();
    }
}
void scheduleTraversals() {
    if (!mTraversalScheduled) {
        mTraversalScheduled = true;
        mTraversalBarrier = mHandler.getLooper().getQueue().postSyncBarrier();
        //回调mTraversalRunnable
        mChoreographer.postCallback(
                Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
        if (!mUnbufferedInputDispatch) {
            scheduleConsumeBatchedInput();
        }
        notifyRendererOfFramePending();
        pokeDrawLockIfNeeded();
    }
}
final class TraversalRunnable implements Runnable {
    @Override
    public void run() {
        doTraversal();
    }
}
void doTraversal() {
    if (mTraversalScheduled) {
        mTraversalScheduled = false;
        mHandler.getLooper().getQueue().removeSyncBarrier(mTraversalBarrier);
        if (mProfile) {
            Debug.startMethodTracing("ViewAncestor");
        }
        //View的绘制发起方法
        performTraversals();
        if (mProfile) {
            Debug.stopMethodTracing();
            mProfile = false;
        }
    }
}

终于走到这里了上面调用了performTraversals();方法。它是我们整个View绘制流程的核心方法也是绘制流程的起始方法

    private void performTraversals() {
        // Ask host how big it wants to be
        performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
        performLayout(lp, mWidth, mHeight);
        performDraw();
    }

performTraversals()的内容太多了我们这里只看上面三个方法。分别引导了View的测量、布局和绘制流程。具体每个方法的作用我们就在下个章节来讲解。

相关文章

网友评论

      本文标题:View的绘制流程三、DecorView的添加

      本文链接:https://www.haomeiwen.com/subject/zjdumxtx.html