深入解析Android中View的工作原理

AI应用架构师总结:智能问答系统用户意图识别的8种方法与实践! 意图识别是智能问答系统的大脑入口,其技术水平决定了系统能否准确捕捉用户的核心诉求。本文系统剖析了从基础规则到前沿PLM的8种核心意图识别方法透明简单,冷启动快,维护成本高。中等规模场景基线,依赖特征工程。利用词义和局部/序列信息,训练成本高。当前最优精度,需大量资源。添加意图灵活,冷启动友好,精度可能略逊。提升鲁棒性,系统变复杂。解决歧义和自然交互的关键(多轮)。增强专业领域理解和推理能力。成功的意图识别模块需要:精准的意图定义(Schema)是前提! 阅读详情

Android中的任何一个布局、任何一个控件其实都是直接或间接继承自View实现的,当然也包括我们在平时开发中所写的各种炫酷的自定义控件了,所以学习View的工作原理对于我们来说显得格外重要,本篇博客,我们将一起深入学习Android中View的工作原理。

ViewRoot和DecorView

1.ViewRoot对应于ViewRootImpl类,是连接WindowManager和DecorView的纽带,View的三大流程均是通过ViewRoot来完成的。在ActivityThread中,当Activity对象被创建完毕后,会将DecorView添加到Window中,同时会创建ViewRootImpl对象,并将ViewRootImpl对象和DecorView建立关联。

2.View的绘制流程从ViewRoot的performTraversals开始,经过measure、layout和draw三个过程才可以把一个View绘制出来,其中measure用来测量View的宽高,layout用来确定View在父容器中的放置位置,而draw则负责将View绘制到屏幕上。

3.performTraversals会依次调用performMeasure、performLayout和performDraw三个方法,这三个方法分别完成顶级View的measure、layout和draw这三大流程。其中performMeasure中会调用measure方法,在measure方法中又会调用onMeasure方法,在onMeasure方法中则会对所有子元素进行measure过程,这样就完成了一次measure过程;子元素会重复父容器的measure过程,如此反复完成了整个View数的遍历。

这里写图片描述

这里写图片描述

measure过程决定了View的宽/高,完成后可通过getMeasuredWidth/getMeasureHeight方法来获取View测量后的宽/高。Layout过程决定了View的四个顶点的坐标和实际View的宽高,完成后可通过getTop、getBotton、getLeft和getRight拿到View的四个定点坐标。Draw过程决定了View的显示,完成后View的内容才能呈现到屏幕上。

DecorView作为顶级View,一般情况下它内部包含了一个竖直方向的LinearLayout,里面分为两个部分(具体情况和Android版本和主题有关),上面是标题栏,下面是内容栏。在Activity通过setContextView所设置的布局文件其实就是被加载到内容栏之中的。

//获取内容栏
ViewGroup content = findViewById(R.android.id.content);
//获取我们设置的Viewcontext.getChildAt(0);
DecorView其实是一个FrameLayout,View层的事件都先经过DecorView,然后才传给我们的View。

这里写图片描述

这里写图片描述

MeasureSpec

1.MeasureSpec很大程度上决定一个View的尺寸规格,测量过程中,系统会将View的layoutParams根据父容器所施加的规则转换成对应的MeasureSpec,再根据这个measureSpec来测量出View的宽/高。 2.MeasureSpec代表一个32位的int值,高2位为SpecMode,低30位为SpecSize,SpecMode是指测量模式,SpecSize是指在某种测量模式下的规格大小。

MpecMode有三类; 1.UNSPECIFIED 父容器不对View进行任何限制,要多大给多大,一般用于系统内部 2.EXACTLY 父容器检测到View所需要的精确大小,这时候View的最终大小就是SpecSize所指定的值,对应LayoutParams中的match_parent和具体数值这两种模式。 3.AT_MOST 父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,不同View实现不同,对应LayoutParams中的wrap_content。

当View采用固定宽/高的时候,不管父容器的MeasureSpec的是什么,View的MeasureSpec都是精确模式兵其大小遵循Layoutparams的大小。 当View的宽/高是match_parent时,如果他的父容器的模式是精确模式,那View也是精确模式并且大小是父容器的剩余空间;如果父容器是最大模式,那么View也是最大模式并且起大小不会超过父容器的剩余空间。 当View的宽/高是wrap_content时,不管父容器的模式是精确还是最大化,View的模式总是最大化并且不能超过父容器的剩余空间。

对于DecorView,它的MeasureSpec由Window的尺寸和其自身的LayoutParams来共同确定,对于普通的View,其MeasureSpec由父容器的MeasureSpec和自身的Layoutparams来共同确定。

对于 DecorView,在ViewRootImpl源码中的measureHierarchy有如下一段代码:

.........
if (baseSize != 0 && desiredWindowWidth > baseSize) {
                childWidthMeasureSpec = getRootMeasureSpec(baseSize, lp.width);
                childHeightMeasureSpec = getRootMeasureSpec(desiredWindowHeight, lp.height);
                performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
                if (DEBUG_DIALOG) Log.v(TAG, "Window " + mView + ": measured ("
                        + host.getMeasuredWidth() + "," + host.getMeasuredHeight() + ")");
                if ((host.getMeasuredWidthAndState()&View.MEASURED_STATE_TOO_SMALL) == 0) {
                    goodMeasure = true;
.........

我们查看一下getRootMeasureSpec方法的源码:

 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

从上面的代码中就可以很容理解DecorView的MeasureSpec是如何产生的,rootDimension就是DecorView自身的LayoutParams,然后会根据这个值进行判断 LayoutParams.MATCH_PARENT:DecorView的MeasureSpec被赋值为精确模式,DecorView的大小就是Window的大小

ViewGroup.LayoutParams.WRAP_CONTENT:DecorView的MeasureSpec被赋值为最大模式,DecorView的大小不定,但是不能超过Window的大小

默认情况:DecorView的MeasureSpec被赋值为精确模式,DecorView的大小为自身LayoutParams设置的值,也就是rootDimension

接着是对于普通的View,也就是布局中的View,它的Measure过程由ViewGroup传递而来,其中有一个方法是measureChildWithMargins

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

        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);
    }

在对子view进行measure之前会先调用getChildMeasureSpec方法来获取子view的MeasureSpec,从这段代码就可以看出来子view的MeasureSpec的确定与父容器的MeasureSpec(parentWidthMeasureSpec)还有自身的LayoutParams(lp.height和lp.width),还有View自己的Margin和Padding有关

接下来查看getChildMeasureSpec方法源码:

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 him 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;
        }
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

这里参数中的padding是指父容器的padding,这里是父容器所占用的空间,所以子view能使用的空间要减去这个padding的值。同时这个方法内部其实就是根据父容器的MeasureSpec结合子view的LayoutParams来确定子view的MeasureSpec

View的绘制流程

measure的过程 如果只是一个View,那么通过measure方法就完成了其测量的过程,如果是一个ViewGroup,除了测量自身外,还会调用子孩子的measure方法

1.View的measure过程 View的measure过程由其measure方法完成,其中有下面一段内容

.........
int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :
                    mMeasureCache.indexOfKey(key);
            if (cacheIndex < 0 || sIgnoreMeasureCache) {
                // measure ourselves, this should set the measured dimension flag back
                onMeasure(widthMeasureSpec, heightMeasureSpec);
                mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            } else {
                long value = mMeasureCache.valueAt(cacheIndex);
                // Casting a long to int drops the high 32 bits, no mask needed
                setMeasuredDimensionRaw((int) (value >> 32), (int) value);
                mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
            }
.........

可以知道View的measure方法内,其实调用了自身的onMeasure方法

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
                getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}
//里面有一个getDefaultSize方法
public static int getDefaultSize(int size, int measureSpec) {
        int result = size;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        switch (specMode) {
        case MeasureSpec.UNSPECIFIED:
            result = size;
            break;
        case MeasureSpec.AT_MOST:
        case MeasureSpec.EXACTLY:
            result = specSize;
            break;
        }
        return result;
    }

一般我们只需要看MeasureSpec.AT_MOST和MeasureSpec.EXACTLY两种情况,这两种情况返回的result其实都是measureSpec中取得的specSize,这个specSize就是View测量后的大小,这里之所以是View测量后的大小,是因为View的最终大小是在layout阶段确定的,所以要加已区分,一般情况下View测量大小和最终大小是一样的。

UNSPECIFIED情况下,result的值就是getSuggestedMinimumWidth()方法和getSuggestedMinimumHeight()返回的值,查看这两个方法

protected int getSuggestedMinimumWidth() {
        return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());
    }


protected int getSuggestedMinimumHeight() {
        return (mBackground == null) ? mMinHeight : max(mMinHeight, mBackground.getMinimumHeight());

}

从getSuggestedMinimumWidth代码可以看出,如果View没有设置背景,那么宽度就为mMinWidth,这个值对应android:minWidth这个属性所设定的值,如果View设置了背景,则为max(mMinWidth, mBackground.getMinimumWidth())

 public int getMinimumWidth() {
        final int intrinsicWidth = getIntrinsicWidth();
        return intrinsicWidth > 0 ? intrinsicWidth : 0;
    }

查看mBackground.getMinimumWidth()方法,它其实是Drawable的方法,如果intrinsicHeight也就是原始的宽度不为0,就返回它,如果为0,就返回0。

从View的getDefaultSize方法可以得出结论:View的宽高由specSize决定,如果我们通过继承View来自定义控件需要重写onMeasure方法,并设置WRAP_CONTENT时的大小,否则在布局中使用WRAP_CONTENT相当于使用MATCH_PARENT

原因:因为View在布局中使用WRAP_CONTENT就相当于specMode为AT_MOST,而这种情况下,result = specSize,这个specSize的大小为parentSize, parentSize就是父容器目前可用的大小,也就是父容器当前剩余空间的大小,那这时候和在布局中使用MATCH_PARENT效果是一样的

所以在AT_MOST模式下,我们一般都会给View设定默认的内部宽高,并在WRAP_CONTENT时设置此宽高即可。 可以通过查看TextView、ImageView的源码,可以得知在WRAP_CONTENT下,onMeasure方法均做了特殊的处理,下面是TextView的onMeasure中的一段内容

if (widthMode == MeasureSpec.AT_MOST) {
                width = Math.min(widthSize, width);
            }

2.ViewGroup的measure流程 ViewGroup是一个抽象类,它没有重写View的onMeasure方法,而是自己提供了一个measureChildren方法

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }

里面会对子元素进行遍历,然后调用measureChild方法去测量每一个子元素的宽高

protected void measureChild(View child, int parentWidthMeasureSpec,
            int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();

        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
                mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
                mPaddingTop + mPaddingBottom, lp.height);

        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}

在对子view进行measure之前会先调用getChildMeasureSpec方法来获取子孩子的MeasureSpec,从这段代码就可以看出来子view的MeasureSpec的确定与父容器的MeasureSpec(parentWidthMeasureSpec和parentHeightMeasureSpec)还有自身的LayoutParams(lp.height和lp.width),还有View自己的Margin和Padding有关,最后就是调用子view的measure方法

ViewGroup并没有去定义测量的具体过程,这是因为ViewGroup是一个抽象类,其onMeasure方法需要各个子类去实现,因为每个ViewGroup的实现类,例如LinearLayout,RelativeLayout等的布局方式都是不同的,所以不可能一概而论的来写onMeasure方法。

接下来分析LinearLayout的onMeasure方法:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mOrientation == VERTICAL) {
            measureVertical(widthMeasureSpec, heightMeasureSpec);
        } else {
            measureHorizontal(widthMeasureSpec, heightMeasureSpec);
        }
}

查看measureVertical方法

// See how tall everyone is. Also remember max width.
        for (int i = 0; i < count; ++i) {
            final View child = getVirtualChildAt(i);

            if (child == null) {
                mTotalLength += measureNullChild(i);
                continue;
            }

            if (child.getVisibility() == View.GONE) {
               i += getChildrenSkipCount(child, i);
               continue;
            }

            if (hasDividerBeforeChildAt(i)) {
                mTotalLength += mDividerHeight;
            }

            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) child.getLayoutParams();

            totalWeight += lp.weight;

            if (heightMode == MeasureSpec.EXACTLY && lp.height == 0 && lp.weight > 0) {
                // Optimization: don't bother measuring children who are going to use
                // leftover space. These views will get measured again down below if
                // there is any leftover space.
                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + lp.topMargin + lp.bottomMargin);
                skippedMeasure = true;
            } else {
                int oldHeight = Integer.MIN_VALUE;

                if (lp.height == 0 && lp.weight > 0) {
                    // heightMode is either UNSPECIFIED or AT_MOST, and this
                    // child wanted to stretch to fill available space.
                    // Translate that to WRAP_CONTENT so that it does not end up
                    // with a height of 0
                    oldHeight = 0;
                    lp.height = LayoutParams.WRAP_CONTENT;
                }

                // Determine how big this child would like to be. If this or
                // previous children have given a weight, then we allow it to
                // use all available space (and we will shrink things later
                // if needed).
                measureChildBeforeLayout(
                       child, i, widthMeasureSpec, 0, heightMeasureSpec,
                       totalWeight == 0 ? mTotalLength : 0);

                if (oldHeight != Integer.MIN_VALUE) {
                   lp.height = oldHeight;
                }

                final int childHeight = child.getMeasuredHeight();
                final int totalLength = mTotalLength;
                mTotalLength = Math.max(totalLength, totalLength + childHeight + lp.topMargin +
                       lp.bottomMargin + getNextLocationOffset(child));

                if (useLargestChild) {
                    largestChildHeight = Math.max(childHeight, largestChildHeight);
                }
            }

            /**
             * If applicable, compute the additional offset to the child's baseline
             * we'll need later when asked {@link #getBaseline}.
             */
            if ((baselineChildIndex >= 0) && (baselineChildIndex == i + 1)) {
               mBaselineChildTop = mTotalLength;
            }

            // if we are trying to use a child index for our baseline, the above
            // book keeping only works if there are no children above it with
            // weight.  fail fast to aid the developer.
            if (i < baselineChildIndex && lp.weight > 0) {
                throw new RuntimeException("A child of LinearLayout with index "
                        + "less than mBaselineAlignedChildIndex has weight > 0, which "
                        + "won't work.  Either remove the weight, or don't set "
                        + "mBaselineAlignedChildIndex.");
            }

            boolean matchWidthLocally = false;
            if (widthMode != MeasureSpec.EXACTLY && lp.width == LayoutParams.MATCH_PARENT) {
                // The width of the linear layout will scale, and at least one
                // child said it wanted to match our width. Set a flag
                // indicating that we need to remeasure at least that view when
                // we know our width.
                matchWidth = true;
                matchWidthLocally = true;
            }

            final int margin = lp.leftMargin + lp.rightMargin;
            final int measuredWidth = child.getMeasuredWidth() + margin;
            maxWidth = Math.max(maxWidth, measuredWidth);
            childState = combineMeasuredStates(childState, child.getMeasuredState());

            allFillParent = allFillParent && lp.width == LayoutParams.MATCH_PARENT;
            if (lp.weight > 0) {
                /*
                 * Widths of weighted Views are bogus if we end up
                 * remeasuring, so keep them separate.
                 */
                weightedMaxWidth = Math.max(weightedMaxWidth,
                        matchWidthLocally ? margin : measuredWidth);
            } else {
                alternativeMaxWidth = Math.max(alternativeMaxWidth,
                        matchWidthLocally ? margin : measuredWidth);
            }

            i += getChildrenSkipCount(child, i);
        }

遍历子元素,调用他们的measureChildBeforeLayout方法,这个方法内会测量子孩子的宽高,并且有一个mTotalLength来记录LinearLayout 在竖直方向的初步高度,每测量一次子元素,mTotalLength都会增加,增加部分包括子元素的高度以及子元素竖直方向的margin

void measureChildBeforeLayout(View child, int childIndex,
            int widthMeasureSpec, int totalWidth, int heightMeasureSpec,
            int totalHeight) {
        measureChildWithMargins(child, widthMeasureSpec, totalWidth,
                heightMeasureSpec, totalHeight);
    }
里面调用了child.measure方法,也就是子孩子的measure方法
protected void measureChildWithMargins(View child,
            int parentWidthMeasureSpec, int widthUsed,
            int parentHeightMeasureSpec, int heightUsed) {
        final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

        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);
}

当子元素测量完毕后,LinearLayout会测量自身的大小,对于竖直的LinearLayout,它在水平方向上的测量过程,遵循View的测量过程,在竖直方向上,如果采用的是match_parent或者具体的数值,那么它的测量过程和View的一致,即高度为specSize;如果它的布局中高度采用wrap_content,那么高度是子元素所占用的高度总和,但这个和不能超过父容器的剩余空间,当然还要考虑padding,竖直方向的结论可以从下面代码得知:

public static int resolveSizeAndState(int size, int measureSpec, int childMeasuredState) {
        final int specMode = MeasureSpec.getMode(measureSpec);
        final int specSize = MeasureSpec.getSize(measureSpec);
        final int result;
        switch (specMode) {
            case MeasureSpec.AT_MOST:
                if (specSize < size) {
                    result = specSize | MEASURED_STATE_TOO_SMALL;
                } else {
                    result = size;
                }
                break;
            case MeasureSpec.EXACTLY:
                result = specSize;
                break;
            case MeasureSpec.UNSPECIFIED:
            default:
                result = size;
        }
        return result | (childMeasuredState & MEASURED_STATE_MASK);
}

有时候onMeasure中拿到的测量宽高可能是不准确的,比较好的习惯是在onLayout中去获取View的测量宽高和最终宽高

在Activity中,在onCreate,onStart,onResume中均无法正确获得View的宽高信息,这是因为measure和Activity的生命周期是不同步的,所以很可能View没有测量完毕,获得的宽高是0.

measure总结 1.measure过程主要就是从顶层父View向子View递归调用view.measure方法(measure中又回调onMeasure方法)的过程。具体measure核心主要有如下几点:

2.MeasureSpec(View的内部类)测量规格为int型,值由高2位规格模式specMode和低30位具体尺寸specSize组成。其中specMode只有三种值:

MeasureSpec.EXACTLY //确定模式,父View希望子View的大小是确定的,由specSize决定;
MeasureSpec.AT_MOST //最多模式,父View希望子View的大小最多是specSize指定的值;
MeasureSpec.UNSPECIFIED //未指定模式,父View完全依据子View的设计值来决定;

3.View的measure方法是final的,不允许重载,View子类只能重载onMeasure来完成自己的测量逻辑。

4.最顶层DecorView测量时的MeasureSpec是由ViewRootImpl中getRootMeasureSpec方法确定的(LayoutParams宽高参数均为MATCH_PARENT,specMode是EXACTLY,specSize为物理屏幕大小)。

5.ViewGroup类提供了measureChild,measureChild和measureChildWithMargins方法,简化了父子View的尺寸计算。

6.只要是ViewGroup的子类就必须要求LayoutParams继承子MarginLayoutParams,否则无法使用layout_margin参数。

7.View的布局大小由父View和子View共同决定。

8.使用View的getMeasuredWidth()和getMeasuredHeight()方法来获取View测量的宽高,必须保证这两个方法在onMeasure流程之后被调用才能返回有效值。

layout的过程 ViewGroup的位置确定后,它在onLayout中会遍历所有的子元素并调用子元素layout方法,子元素layout方法中又会调用onLayout方法,View的layout方法确定自身的位置,而onLayout方法方法确定子孩子的位置

public void layout(int l, int t, int r, int b) {
        if ((mPrivateFlags3 & PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT) != 0) {
            onMeasure(mOldWidthMeasureSpec, mOldHeightMeasureSpec);
            mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;
        }

        int oldL = mLeft;
        int oldT = mTop;
        int oldB = mBottom;
        int oldR = mRight;

        boolean changed = isLayoutModeOptical(mParent) ?
                setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);

        if (changed || (mPrivateFlags & PFLAG_LAYOUT_REQUIRED) == PFLAG_LAYOUT_REQUIRED) {
            onLayout(changed, l, t, r, b);
            mPrivateFlags &= ~PFLAG_LAYOUT_REQUIRED;

            ListenerInfo li = mListenerInfo;
            if (li != null && li.mOnLayoutChangeListeners != null) {
                ArrayList<OnLayoutChangeListener> listenersCopy =
                        (ArrayList<OnLayoutChangeListener>)li.mOnLayoutChangeListeners.clone();
                int numListeners = listenersCopy.size();
                for (int i = 0; i < numListeners; ++i) {
                    listenersCopy.get(i).onLayoutChange(this, l, t, r, b, oldL, oldT, oldR, oldB);
                }
            }
        }

        mPrivateFlags &= ~PFLAG_FORCE_LAYOUT;
        mPrivateFlags3 |= PFLAG3_IS_LAID_OUT;
}

layout方法的大致流程如下:首先会通过setFrame方法来确定mLeft;mTop;mBottom; mRight;只要这四个点一旦确定,那么View在父容器中的位置就确定了,接着会调用onLayout方法,该方法目的是父容器来确定子元素的位置,无论是View还是ViewGroup都没有实现onLayout方法,我们查看LinearLayout的onLayout方法

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mOrientation == VERTICAL) {
            layoutVertical(l, t, r, b);
        } else {
            layoutHorizontal(l, t, r, b);
        }
}

查看layoutVertical中关键代码

for (int i = 0; i < count; i++) {
            final View child = getVirtualChildAt(i);
            if (child == null) {
                childTop += measureNullChild(i);
            } else if (child.getVisibility() != GONE) {
                final int childWidth = child.getMeasuredWidth();
                final int childHeight = child.getMeasuredHeight();

                final LinearLayout.LayoutParams lp =
                        (LinearLayout.LayoutParams) child.getLayoutParams();

                int gravity = lp.gravity;
                if (gravity < 0) {
                    gravity = minorGravity;
                }
                final int layoutDirection = getLayoutDirection();
                final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
                switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                    case Gravity.CENTER_HORIZONTAL:
                        childLeft = paddingLeft + ((childSpace - childWidth) / 2)
                                + lp.leftMargin - lp.rightMargin;
                        break;

                    case Gravity.RIGHT:
                        childLeft = childRight - childWidth - lp.rightMargin;
                        break;

                    case Gravity.LEFT:
                    default:
                        childLeft = paddingLeft + lp.leftMargin;
                        break;
                }

                if (hasDividerBeforeChildAt(i)) {
                    childTop += mDividerHeight;
                }

                childTop += lp.topMargin;
                setChildFrame(child, childLeft, childTop + getLocationOffset(child),
                        childWidth, childHeight);
                childTop += childHeight + lp.bottomMargin + getNextLocationOffset(child);

                i += getChildrenSkipCount(child, i);
            }
        }

这个方法会遍历所有的子元素并调用setChildFrame方法来为子元素指定对应的位置,其中childTop的数值会不断的增大,这意味着后面的子元素还位于靠下的位置,刚好符合竖直的LinearLayout的特性,setChildFrame方法中不过是调用了子元素的Layout方法而已

private void setChildFrame(View child, int left, int top, int width, int height) {        
        child.layout(left, top, left + width, top + height);
}

同时,会发现setChildFrame中的width和height实际上就是子元素的测量宽高

final int childWidth = child.getMeasuredWidth();
             final int childHeight = child.getMeasuredHeight();

View的layout方法中会通过setFrame方法去设置子元素四个顶点的位置,这样子元素的位置就可以确定

int oldWidth = mRight - mLeft;
            int oldHeight = mBottom - mTop;
            int newWidth = right - left;
            int newHeight = bottom - top;
            boolean sizeChanged = (newWidth != oldWidth) || (newHeight != oldHeight);

            // Invalidate our old position
            invalidate(sizeChanged);

            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            mRenderNode.setLeftTopRightBottom(mLeft, mTop, mRight, mBottom);

接下来是View的getWidth和getHeight方法,结合里面的实现,可以发现他们分别返回的就是View测量的宽度和高度

@ViewDebug.ExportedProperty(category = "layout")
    public final int getWidth() {
        return mRight - mLeft;
    }

    /**
     * Return the height of your view.
     *
     * @return The height of your view, in pixels.
     */
    @ViewDebug.ExportedProperty(category = "layout")
    public final int getHeight() {
        return mBottom - mTop;
}

layout总结 1.layout也是从顶层父View向子View的递归调用view.layout方法的过程,即父View根据上一步measure子View所得到的布局大小和布局参数,将子View放在合适的位置上。

2.View.layout方法可被重载,ViewGroup.layout为final的不可重载,ViewGroup.onLayout为abstract的,子类必须重载实现自己的位置逻辑。

3.measure操作完成后得到的是对每个View经测量过的measuredWidth和measuredHeight,layout操作完成之后得到的是对每个View进行位置分配后的mLeft、mTop、mRight、mBottom,这些值都是相对于父View来说的。

4.凡是layout_XXX的布局属性基本都针对的是包含子View的ViewGroup的,当对一个没有父容器的View设置相关layout_XXX属性是没有任何意义的。

5.使用View的getWidth()和getHeight()方法来获取View测量的宽高,必须保证这两个方法在onLayout流程之后被调用才能返回有效值。 draw的过程 View的绘制过程遵循以下几步: 1)绘制背景background.draw(canvas) 2)绘制自己(onDraw) 3)绘制 children(dispatchDraw) 4)绘制装饰(onDrawScrollBars)

public void draw(Canvas canvas) {
        final int privateFlags = mPrivateFlags;
        final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
                (mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
        mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;

        /*
         * Draw traversal performs several drawing steps which must be executed
         * in the appropriate order:
         *
         *      1. Draw the background
         *      2. If necessary, save the canvas' layers to prepare for fading
         *      3. Draw view's content
         *      4. Draw children
         *      5. If necessary, draw the fading edges and restore layers
         *      6. Draw decorations (scrollbars for instance)
         */

        // Step 1, draw the background, if needed
        int saveCount;

        if (!dirtyOpaque) {
            drawBackground(canvas);
        }

        // skip step 2 & 5 if possible (common case)
        final int viewFlags = mViewFlags;
        boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
        boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
        if (!verticalEdges && !horizontalEdges) {
            // Step 3, draw the content
            if (!dirtyOpaque) onDraw(canvas);

            // Step 4, draw the children
            dispatchDraw(canvas);

            // Overlay is part of the content and draws beneath Foreground
            if (mOverlay != null && !mOverlay.isEmpty()) {
                mOverlay.getOverlayView().dispatchDraw(canvas);
            }

            // Step 6, draw decorations (foreground, scrollbars)
            onDrawForeground(canvas);

            // we're done...
            return;
        }

        /*
         * Here we do the full fledged routine...
         * (this is an uncommon case where speed matters less,
         * this is why we repeat some of the tests that have been
         * done above)
         */

        boolean drawTop = false;
        boolean drawBottom = false;
        boolean drawLeft = false;
        boolean drawRight = false;

        float topFadeStrength = 0.0f;
        float bottomFadeStrength = 0.0f;
        float leftFadeStrength = 0.0f;
        float rightFadeStrength = 0.0f;

        // Step 2, save the canvas' layers
        int paddingLeft = mPaddingLeft;

        final boolean offsetRequired = isPaddingOffsetRequired();
        if (offsetRequired) {
            paddingLeft += getLeftPaddingOffset();
        }

        int left = mScrollX + paddingLeft;
        int right = left + mRight - mLeft - mPaddingRight - paddingLeft;
        int top = mScrollY + getFadeTop(offsetRequired);
        int bottom = top + getFadeHeight(offsetRequired);

        if (offsetRequired) {
            right += getRightPaddingOffset();
            bottom += getBottomPaddingOffset();
        }

        final ScrollabilityCache scrollabilityCache = mScrollCache;
        final float fadeHeight = scrollabilityCache.fadingEdgeLength;
        int length = (int) fadeHeight;

        // clip the fade length if top and bottom fades overlap
        // overlapping fades produce odd-looking artifacts
        if (verticalEdges && (top + length > bottom - length)) {
            length = (bottom - top) / 2;
        }

        // also clip horizontal fades if necessary
        if (horizontalEdges && (left + length > right - length)) {
            length = (right - left) / 2;
        }

        if (verticalEdges) {
            topFadeStrength = Math.max(0.0f, Math.min(1.0f, getTopFadingEdgeStrength()));
            drawTop = topFadeStrength * fadeHeight > 1.0f;
            bottomFadeStrength = Math.max(0.0f, Math.min(1.0f, getBottomFadingEdgeStrength()));
            drawBottom = bottomFadeStrength * fadeHeight > 1.0f;
        }

        if (horizontalEdges) {
            leftFadeStrength = Math.max(0.0f, Math.min(1.0f, getLeftFadingEdgeStrength()));
            drawLeft = leftFadeStrength * fadeHeight > 1.0f;
            rightFadeStrength = Math.max(0.0f, Math.min(1.0f, getRightFadingEdgeStrength()));
            drawRight = rightFadeStrength * fadeHeight > 1.0f;
        }

        saveCount = canvas.getSaveCount();

        int solidColor = getSolidColor();
        if (solidColor == 0) {
            final int flags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;

            if (drawTop) {
                canvas.saveLayer(left, top, right, top + length, null, flags);
            }

            if (drawBottom) {
                canvas.saveLayer(left, bottom - length, right, bottom, null, flags);
            }

            if (drawLeft) {
                canvas.saveLayer(left, top, left + length, bottom, null, flags);
            }

            if (drawRight) {
                canvas.saveLayer(right - length, top, right, bottom, null, flags);
            }
        } else {
            scrollabilityCache.setFadeColor(solidColor);
        }

        // Step 3, draw the content
        if (!dirtyOpaque) onDraw(canvas);

        // Step 4, draw the children
        dispatchDraw(canvas);

        // Step 5, draw the fade effect and restore layers
        final Paint p = scrollabilityCache.paint;
        final Matrix matrix = scrollabilityCache.matrix;
        final Shader fade = scrollabilityCache.shader;

        if (drawTop) {
            matrix.setScale(1, fadeHeight * topFadeStrength);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, right, top + length, p);
        }

        if (drawBottom) {
            matrix.setScale(1, fadeHeight * bottomFadeStrength);
            matrix.postRotate(180);
            matrix.postTranslate(left, bottom);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, bottom - length, right, bottom, p);
        }

        if (drawLeft) {
            matrix.setScale(1, fadeHeight * leftFadeStrength);
            matrix.postRotate(-90);
            matrix.postTranslate(left, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(left, top, left + length, bottom, p);
        }

        if (drawRight) {
            matrix.setScale(1, fadeHeight * rightFadeStrength);
            matrix.postRotate(90);
            matrix.postTranslate(right, top);
            fade.setLocalMatrix(matrix);
            p.setShader(fade);
            canvas.drawRect(right - length, top, right, bottom, p);
        }

        canvas.restoreToCount(saveCount);

        // Overlay is part of the content and draws beneath Foreground
        if (mOverlay != null && !mOverlay.isEmpty()) {
            mOverlay.getOverlayView().dispatchDraw(canvas);
        }

        // Step 6, draw decorations (foreground, scrollbars)
        onDrawForeground(canvas);
}

View的绘制过程的传递是通过dispatchDraw实现的,dispatchdraw会遍历调用所有子元素的draw方法。如此draw事件就一层一层的传递下去。

draw总结 1.如果该View是一个ViewGroup,则需要递归绘制其所包含的所有子View。

2.View默认不会绘制任何内容,真正的绘制都需要自己在子类中实现。

3.View的绘制是借助onDraw方法传入的Canvas类来进行的。

4.在获取画布剪切区(每个View的draw中传入的Canvas)时会自动处理掉padding,子View获取Canvas不用关注这些逻辑,只用关心如何绘制即可。

5.默认情况下子View的ViewGroup.drawChild绘制顺序和子View被添加的顺序一致,但是你也可以重载ViewGroup.getChildDrawingOrder()方法提供不同顺序。

更多Android进阶指南 可以扫码 解锁 《Android十大板块文档》

1.Android车载应用开发系统学习指南(附项目实战)

2.Android Framework学习指南,助力成为系统级开发高手

3.2024最新Android中高级面试题汇总+解析,告别零offer

4.企业级Android音视频开发学习路线+项目实战(附源码)

5.Android Jetpack从入门到精通,构建高质量UI界面

6.Flutter技术解析与实战,跨平台首要之选

7.Kotlin从入门到实战,全方面提升架构基础

8.高级Android插件化与组件化(含实战教程和源码)

9.Android 性能优化实战+360°全方面性能调优

10.Android零基础入门到精通,高手进阶之路

敲代码不易,关注一下吧。ღ( ´・ᴗ・` ) 🤔

CMake教程:C++ CMake自定义find_package并在其它项目使用 find_package 是 CMake 中一个非常重要的命令,用于在系统中找到外部库或包,并将其包含到项目中。: 要查找的包的名称。[version]: 可选的版本号。如果指定了版本号,CMake 会尝试找到该版本或更高版本的包。[REQUIRED]: 如果指定了这个关键字,找不到包时会产生一个错误并终止配置过程。: 指定要查找的包的组件。: 指定可选的组件,即使找不到这些组件,配置过程也会继续。: 指定查找包的模式,CONFIG表示查找配置文件,MODULE表示查找模块文件。 阅读详情

相关推荐

基于深度学习的图像去雨(Opencv,Pytorch,Cnn)

最近做了一个图像去雨项目,使用的语言为Python,深度学习框架为Pytorch。去雨效果不错,具体请看效果视频!图像去雨(GAN,Opencv,Pytorch)

Czqqwer的博客 2612

Android:DecorView

要知道,当用户点击屏幕产生一个触摸行为,这个触摸行为则是通过底层硬件来传递捕获,然后交给ViewRootImpl,接着将事件传递给DecorView,而DecorView再交给PhoneWindow,PhoneWindow再交给Activity,然后接下来就是我们常见的View事件分发了。Window像个承载器,装着内部视图。DecorView作为顶层View,内部包含一个竖直方向的LinearLayout,在这个LinearLayout里面有上中下三部分,分别为ViewStub,标题栏,内容栏。

weixin_51109304的博客 1293

STM32嵌入式开发实战:如何用miniLZO压缩算法节省70%存储空间(附完整工程)

本文详细介绍了如何在STM32嵌入式开发中使用miniLZO无损压缩算法实现高达70%的存储空间节省。通过对比分析不同轻量级算法,重点讲解miniLZO的内存优化配置、分块压缩策略和完整工程实现,帮助开发者有效解决嵌入式系统中的存储瓶颈问题。

ss78901的博客 881

Android 活动、窗、DecorView、ViewRoot

Android 活动、窗、DecorView、ViewRoot

李青涛的博客 1959

终端效率神器:Tmux 安装与使用全指南

终端效率神器:Tmux 安装与使用全指南

身在被窝_心在编程 1357

解决Keil uVision许可证管理中Unknown Product错误

嵌入式开发中,IDE工具的许可证管理是确保开发环境正常运行的关键环节。Keil uVision作为ARM架构的主流开发工具,其许可证系统采用加密验证机制,通过产品版本识别实现授权控制。当出现Unknown Product错误时,通常源于版本兼容性问题或区域发行版差异,这直接影响开发工具链的可用性。特别是在维护历史项目或使用中国特供版时,开发者常会遇到此类问题。通过分析许可证类型、调整安装配置或建立虚拟化开发环境等工程实践方案,可以有效解决这类授权验证故障,保障嵌入式项目的持续集成与交付效率。

weixin_33743248的博客 363

安卓页面绘制流程(2)Window和DecorView的创建

讲解DecorView,ViewRootImpl,Window的关系和创建时机。

分享+记录 2537

YOLOv11改进 | 检测头篇 | 利用动态蛇形卷积DySnakeConv改进yolov11分割检测头(全网独家首发,Segment)

本文给大家带来的最新改进机制是一种我进行优化的专用于分割的检测头,在分割的过程中,最困难的无非就是边缘的检测,动态蛇形卷积(Dynamic Snake Convolution)通过自适应地聚焦于细长和迂回的局部结构,准确地捕捉管状结构的特征。这种卷积方法的核心思想是,通过动态形状的卷积核来增强感知能力,针对管状结构的特征提取进行优化,所以将这个卷积针对于YOLOv11的分割头进行融合是非常合适的,当然本文的检测头也支持用于目标检测,但是我将其设计出来是主要为了分割的读者使用的。

Snu77的博客 3427

java创建activity视图_Android Activity创建到View的显示过程

前言当我们点击桌面图标启动App,到App显示完成,这中间到底经历了什么呢?了解了这部分内容,将会对Activity、Window、View之间联系与区别加深印象,更好指导我们编写代码。通过这篇文章,你将了解到:1、Activity创建到onCreate()、onResume方法执行2、Application创建到onCreate方法执行3、Activity生命周期监听4、Window/Windo...

weixin_42512723的博客 601

【QT/C++】事件过滤器之基于重写 eventFilter 方法的多种常见应用场景及实现

Qt事件过滤器通过重写eventFilter方法实现多种实用功能:1)鼠标事件处理(点击全选文本、禁用滚轮、悬停提示);2)键盘事件处理(输入内容限制、快捷键提交);3)焦点事件处理(自动弹出下拉框、实时验证);4)绘图事件处理(自定义控件绘制);5)窗口事件处理(防止意外关闭、尺寸限制)。事件过滤器提供非侵入式的事件处理方案,相比传统子类化方式更灵活,通过installEventFilter安装到目标控件即可实现各种交互增强功能。

yuhuasheng1997的博客 1483

华为od 面试八股文_测试/测试开发_05_含答案

华为od 面试八股文_测试/测试开发_05_含答案

MISAYAONE的博客 2555

Android高级UI进阶之路(三) —— 理解View的工作原理及自定义View入门

该篇分为上下结构,上部分主要讲解 View 的工作原理,下部分主要以案例的形式讲解自定义 View。ps:该篇文章大部份内容会参考Android 开发艺术探索。更多Android系列教程上传在GitHub:下面我们将详细介绍自定义 View。自定义 View 的作用不用多说,这个大家应该都比较清楚,如果你想做出比较绚丽华彩的 UI 那么仅仅依靠系统的控件是远远不够的,这个时候就必须通过自定义 View 来实现这个绚丽的效果。

金戈鐡馬 754

UI自动化控制PC端微信获取当前群聊的群友列表

在一个月前,某个群友在获取整个群的群友信息时遇到了一点问题: 对整个群进行群友数据获取经测试确实有点棘手,下面我将我的解决过程公布给大家。 基础教程详见: https://blog.youkuaiyun.com/as604049322/article/details/121391639 人工打开要抓取的群聊窗口后,首先获取微信窗口并点击聊天信息按钮: import uiautomation as auto auto.uiautomation.SetGlobalSearchTimeout(1) wechatWind

小小明-代码实体的专栏 3万+

解析Android中View的工作原理

1、下载资源等异步操作的监听器实现时,一定要对用到的所有成员变量判空 IDownloadResultListener mListener = new IDownloadResultListener() { @Override public void onResult(int errorCode) { mHandler.se...

Fly0078的博客 366

Outlook Express 6 (OE6) for Win7/Win8/Win10

英文版 Outlook Express6.0, 兼容Win7/Win10/WinXP,解压就可用。

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

揭开Android View的神秘面纱:深入探索工作原理

在 Android 开发中,自定义 View 是实现个性化界面和独特交互效果的重要手段。根据不同的需求和场景,自定义 View 主要分为以下几种常见类型,每种类型都有其独特的实现要点和挑战。继承 View 类是最基础的自定义 View 方式,适用于需要实现完全自定义的绘制效果,无法通过现有控件组合来实现的场景。在这种方式下,开发者需要重写 onDraw 方法,使用 Canvas 和 Paint 来绘制各种图形、文本和图像,以实现所需的视觉效果。

顾林海 3125

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

探析View工作的原理,真的很简单?

/ 今日科技快讯 /疯狂的“618”结束之后,各大平台相应的给出了“成绩单”。京东数据显示,从2019年6月1日0点到6月18日24点,累计下单金额达2015亿元...

郭霖 333

View的工作原理

View工作原理(一)事件传递原理详解Android事件传递机制源码分析http://blog.youkuaiyun.com/ff20081528/article/details/17353869Android事件传递机制 http://blog.youkuaiyun.com/chenzhiqin20/article/details/8816364View工作原理(二)导致View重建原因http://blog.csdn.

做你所想,想你所做。 443

View工作原理

在自定义View的时候,掌握View的底层工作原理,也就是:View的measure、Layout、draw流程,可以帮助我做出比较有意思的自定义View。因此,本文主要讲解: View的工作原理,其中包括:测量流程、布局流程、绘制流程。 其中包括如下内容: 基础知识准备: 认识ViewRoot和DecorView 理解MeasureSpec MeasureSpec和LayoutParams的

ZhangGeng's Blog 583

android 开发艺术探索和第一行代码,《Android 开发艺术探索》笔记5--View工作原理...

View工作原理.pngViewRoot和DecorView这是在View三大流程之前(measure, layout, draw),需要了解的概念.ViewRoot对应于ViewRootImpl, 它是连接WindowManager和DecorView的纽带. View的三大流程都是通过ViewRoot来完成的. 当一个Activity对象在ActivityThread被创建后. 会将Decor...

weixin_36194553的博客 198

android View的工作原理

上次我们讲了android的滑动冲突,其中也介绍了android的事件分发机制,如果对这方面不清楚的,可以查看我的上一篇博客《android滑动冲突解决方案》,这次我们主要介绍View的工作原理,为以后自定义view定下基础。下面,我讲从以下几方面来讲讲我对View工作原理的理解。 [TOC] 目录 View的UI架构 首先我们来看下UI界面结构图 想必这张图大家都很熟悉,每一个

向梦想攀爬的蜗牛 1008

Android——View的工作原理

View的工作原理 文章目录View的工作原理1.1 ViewRoot和DecorView简介1.1.1 ViewRoot相关1.1.2 DecorView相关1.2 理解MeasureSpec1.2.1 MeasureSpec1.2.2 MeasureSpec和LayoutParams的对应关系1.3 View的工作流程1.3.1 measure过程1.3.2 layout过程1.3.3 dra...

Abfahrt的博客 326

Android View的工作原理

自定义View是一个综合的技术体系,它涉及View的层次结构、事件分发机制和View的工作原理等细节。自定义View的分类1.继承View重新onDraw主要是实现一些不规则的图形。重写onDraw方法。采用这种方式需要自己支持wrap_content, 并且padding也需要自己处理。2.继承ViewGroup派生特殊的Layout。

huaihong1986的博客 979

View工作原理【View树遍历】

原文:

ymangu的专栏 1930

深入了解Android的View工作原理

本文章讲解的内容是深入了解Android的View工作原理,建议对着示例项目阅读文章,示例项目链接如下: ViewDemo 本文章分析的相关的源码基于Android SDK 29(Android 10.0,即Android Q)。 Android的窗口结构 先从Activity的startActivity系列方法开始说起,我选了一个常用的**startActivitiy(Intent intent)**方法,源码如下所示: // Activity.java @Override public void sta

qq_20417381的博客 323

Android高级进阶——View的工作原理Measure过程详解

开篇 本篇主要讲解的是 View 工作原理之 measure 过程,主要是以源码的形式进行分析,源码来源 API 26。 从 ViewRootImpl 的 #performTraversals 方法开始说起 performTraversals 方法是整个工作流程的核心,它里面分别取执行了 measure、layout 以及 draw 三个过程,看一下代码: private void...

AkaiC的博客 614
上一篇: 2024诸多大厂春招提前启动!Android的程序员还在等什么
下一篇: 2024不可缺的Android学习路线图
不秃头de程序猿
博客等级 码龄5年 4089粉丝 1475原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值