首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 移动开发 > Android >

Android中View的作图过程

2012-08-15 
Android中View的绘制过程View可以看成一个树形结构,父控件是父节点,子控件是子节点。View的绘制过程就是遍

Android中View的绘制过程

View可以看成一个树形结构,父控件是父节点,子控件是子节点。View的绘制过程就是遍历这棵树。

View的绘制有三步:

    measure:测量View的Width和Height,layout:布局View(left,right,top,bottom),指定View和手机屏幕的上下左右的距离。draw:绘图

以上的步骤必须按照顺序来。(顺便说一下,以上三个步骤发生在View的构造方法之后。)

一、measure

measure是绘制视图的第一步,因为只有知道的View的大小(Width和Height)才能绘图。

我们在编写layout的xml文件的时候,会遇到layout_width和layout_height两个属性,对于这两个属性我们有三个选择:fill_parent、wrap_content和具体值,measure就是用来处理fill_parent、wrap_content两个属性的,在绘图的时候,要知道具体的值,所以要计算fill_parent、wrap_content的具体值。

下面是几个重要的函数和参数:

    public final void measure(int widthMeasureSpec, int heightMeasureSpec)protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec)protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec)protected void measureChildWithMargins(View child, int parentWidthMeasureSpec, int widthUsed, int parentHeightMeasureSpec, int heightUsed)

前两个方法是View类里面的方法,后三个方法是ViewGroup类里面的方法。


先来看看measure的源码:

    protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {        mMeasuredWidth = measuredWidth;        mMeasuredHeight = measuredHeight;        mPrivateFlags |= MEASURED_DIMENSION_SET;    }

再来看下MeasureSpec这个类,MeasureSpec参数的值为int型,分为高32位和低16为,高32位保存的是specMode,低16位表示specSize,specMode分三种:

    MeasureSpec.UNSPECIFIED:父视图不对子视图施加任何限制,子视图可以得到任意想要的大小MeasureSpec.EXACTLY:父视图希望子视图的大小是specSize中指定的大小MeasureSpec.AT_MOST:子视图的大小最多是specSize中的大小

以上施加的限制只是父视图“希望”子视图的大小按MeasureSpec中描述的那样,但是子视图的具体大小取决于多方面的

热点排行