美文网首页
Android笔记3-View的工作原理

Android笔记3-View的工作原理

作者: android小菜鸡一枚 | 来源:发表于2018-07-11 14:15 被阅读0次

Android开发艺术探讨(View的工作原理)

ViewRoot

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


performTraversals的工作流程图

measure过程决定了View的测量宽高,可通过getMeasuredWidth和getMeasuredHeight方法来获取到View测量后的宽高。
layout过程决定了View的四个顶点的位置和View的最终宽高,可以通过getTop,getBottom,getLeft,getRight来拿到View的四个顶点的位置,并通过getWidth和getHeight方法来拿到View的最终宽高
draw过程将View绘制到屏幕上



DecorView的结构

MeasureSpec

测量规格
MeasureSpec代表一个32位int值,高2位代表SpecMode,低30位代表SpecSize
SpecMode是指测量模式,SpecSize是指在某种测量模式下的规格大小
SpecMode
1.UNSPECIFIED
父容器不对View有任何限制,要多大给多大,一般用于系统内部的测量过程
2.EXACTLY
父容器已经检测出View所需要的精确的大小,这个时候View的最终大小就是SpecSize所指定的值,对应于LayoutParams中的match_parent和具体的数值这两种模式
3.AT_MOST
父容器指定了一个可用大小即SpecSize,View的大小不能大于这个值,对应于LayoutParams中的wrap_content



系统内部是通过MeasureSpec来进行View的测量。
在View测量的时候,系统会将LayoutParams在父容器的约束下转换成对应的MeasureSpec,然后根据这个MeasureSpec来确定View测量后的宽高。LayoutParams需要和父容器一起才能决定View的MeasureSpec。
DecorView(顶级View),其MeasureSpec由窗口的尺寸和其自身的LayoutParams来共同确定的。
普通的View,其MeasureSpec由父容器的MeasureSpec和自身的LayoutParams来共同决定,MeasureSpec一旦确定后,onMeasure中就可以确定View的测量宽高。

ViewGroup#getChildMeasureSpec

根据父容器的MeasureSpec同时结合View本身的LayoutParams来确定子元素的MeasureSpec,padding是指父容器中已占用的空间大小,因此子元素可用的大小为父容器的尺寸减去padding。

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;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }
普通View的MeasureSpec的创建规则

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

View的工作流程

measure过程
1.View的measure过程
由measure方法完成,内部调用onMeasure方法
需要给View指定一个默认的内部宽高(mWidth和mHeight),并在wrap_content时设置此宽高即可,对于非wrap_content情况,沿用系统的测量值。

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
        if (widthSpecMode == MeasureSpec.AT_MOST 
                && heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth,mHeight);
        } else if (widthSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(mWidth,heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(widthSpecSize,mHeight);
        }
    }

2.ViewGroup的measure过程
除了完成自己的measure过程外,还会遍历去调用所有子元素的measure方法


在activity中获取某个View的宽和高?

在onCreate,onStart,onResume中无法正确的发获取某个View的宽高信息,View的measure过程和Activity的生命周期方法不是同步的,View还没有测量完毕,获得的宽高就是0。
解决方法:
1.Activity/View#onWindowFocusChanged会被频繁的调用

public void onWindowFocusChanged(boolean hasFocus) {
        if(hasFocus){
                int width = view.getMeasuredWidth();
                int height = view.getMeasuredHeight();
        }
}

2.view.post(runnable)

view.post(new Runnable) {
  public void run(){
    int width = view.getMeasuredWidth();
    int height = view.getMeasuredHeight();
  }
}

3.ViewTreeObserver 使用OnGlobalLayoutListener接口
当View树的状态发生改变或者View内部的可见性发现改变是,回调onGlobalLayout方法

view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener{
    public void onGlobalLayout(){
        view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
        int width = view.getMeasuredWidth();
        int height = view.getMeasuredHeight();
    }
})

View的getMeasuredWidth和getWidth方法有什么区别

在View的默认实现中,View的测量宽/高和最终宽/高是相等的,只不过测量宽/高形成于View的measure过程,而最终宽/高形成于View的layout过程,两者的赋值时机不同,在日常开发中,我们可以认为View的测量宽/高就等于最终宽/高,但是的确存在某些特殊情况的,如重写View的layout方法:

public void layout(int l,int t,int r,int b) {
  super.layout(l,t,r+100,b+100);
}

layout过程

ViewGroup用来确定子元素的位置,当ViewGroup的位置确定后,它在onLayout中会遍历所有的子元素并调用其layout方法,在layout方法中onLayout方法又会被调用。layout方法确定View本身的位置,而onLayout方法则会确定所有子元素的位置

draw过程

将View绘制到屏幕上
View的绘制过程遵循如下几步:
1.绘制背景background.draw(canvas)
2.绘制自己(onDraw)
3.绘制children(dispatchDraw)
4.绘制装饰(onDrawScrollBars)
View绘制过程的传递是通过dispatchDraw来实现的。dispatchDraw会遍历调用所有子元素的draw方法,如此draw事件就一层层传递下去。

自定义View

自定义View须知
1、让View支持wrap_content

  1. 让View支持padding
  2. 尽量不要在View中使用Handler
  3. View中如果有线程或者动画,需要及时停止
    5、View带有滑动嵌套时,处理滑动冲突

自定义View实现示例

1.继承View重写onDraw方法
需要自己支持wrap_content并且padding也需要自己处理。
对于直接继承自View的控件,如果不对wrap_content做特殊处理,那么使用wrap_content就相当于使用match_parent。
对于wrap_content问题,需要指定一个wrap_content模式的默认宽高即可
对于padding问题,只要在绘制的时候考虑一下padding即可
为其提供自定义属性,如何创建自定义属性:
第一步 在values目录下创建自定义属性的XML,比如attr.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
        <declare-styleable name="CircleView">
                <attr name="circle-color"  format="color" />
        </declare-styleable>
</resources>

第二步 在View的构造方法中解析自定义属性的值并做相应处理

TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CircleView);
mColor = a.getColor(R.styleable.CircleView_circle_color,Color.RED);
a.recycle();

第三步 在布局文件中使用自定义属性
必须在布局文件中添加schema声明:xmlnns:app=http://schemas.android.com/apk/res-auto

2.继承ViewGroup派生特殊的Layout

相关文章

网友评论

      本文标题:Android笔记3-View的工作原理

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