美文网首页
UI 08:View的绘制流程分析

UI 08:View的绘制流程分析

作者: xqiiitan | 来源:发表于2024-06-06 16:09 被阅读0次
DecorView与PhoneWindow关系.png

View 的绘制流程:

mTv.getMeasuredHeight();
setContentView() 源码,换肤的框架。

流程:AppCompatActivity

onCreate-- setContentView-- getDelegate().setContentView(layoutResId)
-- AppCompatDelegateImplV9::setContentView()-- ensureSubDecor()
-- createSubDecor()-- mWindow.getDecorView()


流程:Activity

onCreate-- setContentView-- getWindow().setContentView(layoutResId)
PhoneWindow::setContentView()
-- installDecor()
-- generateDecor()
-- new DecorView()
-- 然后把我们的布局,加到DecorView里面。
只是创建了DecorView,加载我们的布局到了DecorView

mContentParent = generateLayout(mDecor); // 加载系统的布局,里面有个id叫 android.R.id.content
// 把布局加载到DecorView
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);
final View root = inflater.inflate(layoutResource, null);
addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
// 把我们的布局,activity_main, 加载到 mContentParent 里面来。
mLayoutInflater.inflate(layoutResID, mContentParent);

此时,DecorView还没有加载关联到 WindowManager上面,还没有测量。所以此时拿控件的值,还是0。

mTv.post 获取控件宽高值。

mTv.post(new Runnable(){ run(){ }});
-- getRunQueue().post(action); // 加入到一个队列中
-- HandlerActionQueue::post()
-- HandlerActionQueue::postDelayed() 保存action 到Queue中。

会在dispatchAttachedToWindow中执行action。此时,window已经加进来了。在onResume之后执行。

attach到window -- dispatchAttachedToWindow() // 在测量完毕后调用方法
-- mRunQueue.executeActions(info.Handler);
-- HandlerActionQueue::executeActions(handler);
-- handler.postDelayed(handlerAction.action, handlerAction.delay); // 执行run
之所以能拿到控件的宽高值,是因为调用了onMeasure方法。
所以这里,能拿到控件的宽高。

ActivityThread::

Activity 的启动流程:
performLaunchActivity()--> Activity::onCreate()
--> handleResumeActivity()
--> performResumeActivity()-> Activity::onResume() // 还是没测量。
--> wm.addView(decor, l); // 才开始 加载DecorView 到 WindowManager上,
这时才开始 View 的绘制流程(measure(),layout(),draw())。
所以,在这里才能拿到空间的宽高值。

// 里面的view 不能获取宽高。此时并没有加载关联到任何父布局。不会测量,所以宽高信息拿不到。
View view = View.inflate(this, R.layout.activity_main, null);
// 里面的View能获取宽高,因为里面调用了addView方法(进行了测量等动作)
View view = View.inflate(this, R.layout.activity_main, mParentView);
ViewManager::updateViewLayout(decor, l);


ViewRootImpl root; 是在 WindowManagerGlobal 中实例化的。

    root = new ViewRootImpl(view.getContext(), display);
    mRoots.add(root);
    root.setView(view, wparams, panelParentView); // 关键

最最外层是PhoneWindowActivity;ViewRootImpl 是最外层根布局。DecorView是加载在ViewRootImpl中。

1. WindowManagerImpl.java 绘制流程入口:

 // Activity.java  onResume之后流程。
getWindowManager();
    mWindowManager = mWindow.getWindowManager(); // mWindowManager是phoneWindow
Window:: getWindowManager();
    mWindowManager = ((WindowManagerImpl)wm).createLocalWindowManager(this);

 wm.addView(decor, l)-- WindowManagerImpl.addView()
ViewRootImpl 是最外层的根布局。DecorView是加载在ViewRootImpl中。
---> root.setView(view, wparams, panelParentView); // 关键方法。
---> requestLayout()
---> scheduleTraversals()
    mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);
    TraversalRunnable()
---> doTraversal()
---> performTraversals() // 【网上文章,基本从这里开始】
2. 重点方法:
--- performTraversals()
--- performMeasure(childWidthMeasureSpec, childHeightMeasureSpec) // 测量流程中,第一个调用的方法
--> mView.measure(childWidthMeasureSpec, childHeightMeasureSpec); // mView 就是 mDecorView
--> onMeasure(widthMeasureSpec, heightMeasureSpec); // 测量开始了  【Step2】
--> LinearLayout.onMeasure()                        // extends ViewGroup
--> measureVertical()                               // 垂直布局的测量
    // for循环,拿到里面的 子view。
--> measureChildBeforeLayout()
--> measureChildWithMargins()
    测量模式:onMeasure()
    childWidthMeasureSpec, childHeightMeasureSpec 指定宽高测量模式。
    widthMeasureSpec = childWidthMeasureSpec
    heightMeasureSpec = childHeightMeasureSpec
    
--> child.measure(childWidthMeasureSpec, childHeightMeasureSpec) // 再次进入child(LinearLayout)【Step2】.
    测量完毕后,调用setMeasureDimension。
--> setMeasureDimension()
--> setMeasuredDimensionRaw() // 从这开始,布局才真正有宽高信息(给宽高赋了值)。mMeasureHeight/ mMeasureWidth才开始有值。

--> 接着执行 LinearLayout(ViewGroup) 的onMeasure(), 去指定自己的宽高【里面遍历所有childView】。
    `childHeight = child.getMeasuredHeight() + share;` // 垂直方向,高度累加所有childView的高度。
// RelativeLayout的高度的算法,指定子孩子里面最高的。
-->  `setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState), heightSizeAndState);` // 再次计算一下
    private void setMeasuredDimensionRaw(int measuredWidth, int measuredHeight) {
        mMeasuredWidth = measuredWidth; // 设置宽高的值
        mMeasuredHeight = measuredHeight;
        mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;
    }

总结:

  • 测量从外往里面 递归,首先把自己(ViewRoot,DecorView)的测量模式传递给子view,......, 最终for循环,指定TextView的宽高;
  • 从而拿到 child.getMeasuredHeight() 子View的宽高,往外面走(将子View的高度给父容器),
  • 拿到子view的宽高,然后计算自己的宽高。
  • 自己的宽高也会给到它的 父容器,不断的往外面走。

对应的测量模式:
wrap_content: at_most
match_parent, fill_parent, 100dp: exactly

// ViewGroup.java
// 测量的值:父布局的测量模式 + 本身的View宽高。
// 模式和大小 是有父布局和自己决定的:
//      父布局的是包裹内容warp_content,就算子布局是match_parent, 此时计算的测量模式还是at_most.
//      父布局是match_parent, 就算子布局是match_parent, 此时计算的测量模式还是at_most 测量模式.
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    int specMode = MeasureSpec.getMode(spec); // 父布局的宽高,模式
    int specSize = MeasureSpec.getSize(spec); // 父布局的size
    int size = Math.max(0, spacSize - padding);
    int resultSize = resultMode = 0;
    
    switch(specMode) {
      case MeasureSpec.EXACTLY: // 父布局是 指定的值。
      break;
      case MeasureSpec.AT_MOST:
      break;
    }
}

// 最终测量的值:父布局的测量模式mode + 子View设置的宽高 共同决定。

Android [深度 2年左右],底层源码、系统架构,ndk。专注一个方向。然后+广度。
移动互联网刚开始,未来离不开手机。

aidl解决了什么问题?
Activity,window,View三者的区别。


ViewGroup:: getChildMeasureSpec 源码,计算测量模式

protected void measureChildWithMargins(View child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

    // 计算子view的Spec宽高信息。
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                    + widthUsed, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                    + heightUsed, lp.height);
    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

// spec 父容器的spec信息;
// childDimension child view的宽/高信息。
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);
        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let them have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

相关文章

网友评论

      本文标题:UI 08:View的绘制流程分析

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