Android中View的绘制过程 onMeasure方法简述 附有自定义View例子

Android中View的绘制过程

  当Activity获得焦点时,它将被要求绘制自己的布局,Android framework将会处理绘制过程,Activity只需提供它的布局的根节点。

  绘制过程从布局的根节点开始,从根节点开始测量和绘制整个layout tree。

  每一个ViewGroup 负责要求它的每一个孩子被绘制,每一个View负责绘制自己。

  因为整个树是按顺序遍历的,所以父节点会先被绘制,而兄弟节点会按照它们在树中出现的顺序被绘制。

  

  绘制是一个两遍(two pass)的过程:一个measure pass和一个layout pass。

  测量过程(measuring pass)是在measure(int, int)中实现的,是从树的顶端由上到下进行的。

  在这个递归过程中,每一个View会把自己的dimension specifications传递下去。

  在measure pass的最后,每一个View都存储好了自己的measurements,即测量结果。

  第二个是布局过程(layout pass),它发生在 layout(int, int, int, int)中,仍然是从上到下进行(top-down)。

  在这一遍中,每一个parent都会负责用测量过程中得到的尺寸,把自己的所有孩子放在正确的地方。

尺寸的父子关系处理

  当一个View对象的 measure() 方法返回时,它的 getMeasuredWidth() 和 getMeasuredHeight()值应该被设置好了,并且它的所有子孙的值也应该一起被设置好了。

  一个View对象的measured width 和measured height的值必须考虑到它的父容器给它的限制。

  这样就保证了在measure pass的最后,所有的parent都接受了它的所有孩子的measurements结果。

  注意:一个parent可能会不止一次地对它的孩子调用measure()方法。

  比如,第一遍的时候,一个parent可能测量它的每一个孩子,并没有指定尺寸,parent只是为了发现它们想要多大;

  如果第一遍之后得知,所有孩子的无限制的尺寸总和太大或者太小,parent会再次对它的孩子调用measure()方法,这时候parent会设定规则,介入这个过程,使用实际的值。

  (即,让孩子自由发展不成,于是家长介入)。

布局属性说明

  LayoutParams是View用来告诉它的父容器它想要怎样被放置的参数。

  最基本的LayoutParams基类仅仅描述了View想要多大,即指明了尺寸属性。

  即View在XML布局时通常需要指明的宽度和高度属性。

  每一个维度都可以指定成下列三种值之一:

  1.FILL_PARENT (API Level 8之后重命名为MATCH_PARENT),表示View想要尽量和它的parent一样大(减去边距)。

  2.WRAP_CONTENT,表示View想要刚好大到可以包含它的内容(包括边距)。

  3.具体的数值

  ViewGroup的不同子类(不同的布局类)有相应的LayoutParams子类,其中会包含更多的布局相关属性。

onMeasure方法

  onMeasure方法是测量view和它的内容,决定measured width和measured height的,这个方法由 measure(int, int)方法唤起,子类可以覆写onMeasure来提供更加准确和有效的测量。

  有一个约定:在覆写onMeasure方法的时候,必须调用 setMeasuredDimension(int,int)来存储这个View经过测量得到的measured width and height。

  如果没有这么做,将会由measure(int, int)方法抛出一个IllegalStateException

  onMeasure方法的声明如下:

protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec)

  其中两个输入参数:

  widthMeasureSpec

  heightMeasureSpec

  分别是parent提出的水平和垂直的空间要求

  这两个要求是按照View.MeasureSpec类来进行编码的。

  参见View.MeasureSpec这个类的说明:这个类包装了从parent传递下来的布局要求,传递给这个child。

  每一个MeasureSpec代表了对宽度或者高度的一个要求。

  每一个MeasureSpec有一个尺寸(size)和一个模式(mode)构成。

  MeasureSpecs这个类提供了把一个<size, mode>的元组包装进一个int型的方法,从而减少对象分配。当然也提供了逆向的解析方法,从int值中解出size和mode。

  有三种模式:

  UNSPECIFIED

  这说明parent没有对child强加任何限制,child可以是它想要的任何尺寸。

  EXACTLY

  Parent为child决定了一个绝对尺寸,child将会被赋予这些边界限制,不管child自己想要多大。

  AT_MOST

  Child可以是自己任意的大小,但是有个绝对尺寸的上限。

  覆写onMeasure方法的时候,子类有责任确保measured height and width至少为这个View的最小height和width。

  (getSuggestedMinimumHeight() and getSuggestedMinimumWidth())。

onLayout

  这个方法是在layout pass中被调用的,用于确定View的摆放位置和大小。方法声明:

protected void onLayout (boolean changed, int left, int top, int right, int bottom)

  其中的上下左右参数都是相对于parent的。

  如果View含有child,那么onLayout中需要对每一个child进行布局。

自定义View Demo

  API Demos中的LabelView类是一个继承自View的自定义类的例子:

/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package com.example.android.apis.view; // Need the following import to get access to the app resources, since this
// class is in a sub-package.
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View; import com.example.android.apis.R; /**
* Example of how to write a custom subclass of View. LabelView
* is used to draw simple text views. Note that it does not handle
* styled text or right-to-left writing systems.
*
*/
public class LabelView extends View {
private Paint mTextPaint;
private String mText;
private int mAscent; /**
* Constructor. This version is only needed if you will be instantiating
* the object manually (not from a layout XML file).
* @param context
*/
public LabelView(Context context) {
super(context);
initLabelView();
} /**
* Construct object, initializing with any attributes we understand from a
* layout file. These attributes are defined in
* SDK/assets/res/any/classes.xml.
*
* @see android.view.View#View(android.content.Context, android.util.AttributeSet)
*/
public LabelView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView(); TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.LabelView); CharSequence s = a.getString(R.styleable.LabelView_text);
if (s != null) {
setText(s.toString());
} // Retrieve the color(s) to be used for this view and apply them.
// Note, if you only care about supporting a single color, that you
// can instead call a.getColor() and pass that to setTextColor().
setTextColor(a.getColor(R.styleable.LabelView_textColor, 0xFF000000)); int textSize = a.getDimensionPixelOffset(R.styleable.LabelView_textSize, 0);
if (textSize > 0) {
setTextSize(textSize);
} a.recycle();
} private final void initLabelView() {
mTextPaint = new Paint();
mTextPaint.setAntiAlias(true);
// Must manually scale the desired text size to match screen density
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
setPadding(3, 3, 3, 3);
} /**
* Sets the text to display in this label
* @param text The text to display. This will be drawn as one line.
*/
public void setText(String text) {
mText = text;
requestLayout();
invalidate();
} /**
* Sets the text size for this label
* @param size Font size
*/
public void setTextSize(int size) {
// This text size has been pre-scaled by the getDimensionPixelOffset method
mTextPaint.setTextSize(size);
requestLayout();
invalidate();
} /**
* Sets the text color for this label.
* @param color ARGB value for the text
*/
public void setTextColor(int color) {
mTextPaint.setColor(color);
invalidate();
} /**
* @see android.view.View#measure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
} /**
* Determines the width of this view
* @param measureSpec A measureSpec packed into an int
* @return The width of the view, honoring constraints from measureSpec
*/
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = (int) mTextPaint.measureText(mText) + getPaddingLeft()
+ getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
} return result;
} /**
* Determines the height of this view
* @param measureSpec A measureSpec packed into an int
* @return The height of the view, honoring constraints from measureSpec
*/
private int measureHeight(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec); mAscent = (int) mTextPaint.ascent();
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text (beware: ascent is a negative number)
result = (int) (-mAscent + mTextPaint.descent()) + getPaddingTop()
+ getPaddingBottom();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
return result;
} /**
* Render the text
*
* @see android.view.View#onDraw(android.graphics.Canvas)
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawText(mText, getPaddingLeft(), getPaddingTop() - mAscent, mTextPaint);
}
}

参考资料

  API Guides:How Android Draws Views

  http://developer.android.com/guide/topics/ui/how-android-draws.html

  API Guides:Custom Components

  http://developer.android.com/guide/topics/ui/custom-components.html

  View onMeasure:

  http://developer.android.com/reference/android/view/View.html

  ViewGroup.LayoutParams:

  http://developer.android.com/reference/android/view/ViewGroup.LayoutParams.html

Android中View的绘制过程 onMeasure方法简述 附有自定义View例子的更多相关文章

  1. 【转】Android中View的绘制过程 onMeasure方法简述 附有自定义View例子

    Android中View的绘制过程 当Activity获得焦点时,它将被要求绘制自己的布局,Android framework将会处理绘制过程,Activity只需提供它的布局的根节点. 绘制过程从布 ...

  2. Android UI 绘制过程浅析(五)自定义View

    前言 这已经是Android UI 绘制过程浅析系列文章的第五篇了,不出意外的话也是最后一篇.再次声明一下,这一系列文章,是我在拜读了csdn大牛郭霖的博客文章<带你一步步深入了解View> ...

  3. Android 自定义 view(四)—— onMeasure 方法理解

    前言: 前面我们已经学过<Android 自定义 view(三)-- onDraw 方法理解>,那么接下我们还需要继续去理解自定义view里面的onMeasure 方法 推荐文章: htt ...

  4. android 中view的绘制过程

    view的绘制过程中分别会执行:onMeasure(会多次)计算view的大小,OnLayout(),确定控件的大小和位置 onDraw()绘制view 当Activity获得焦点时,它将被要求绘制自 ...

  5. Android View的绘制过程

    首先是view的绘制过程~最主要的分三部分 measure layout draw 看字面意思,计算,布局,画~ android中控件相当于是画在一个无限大的画布上的,那就产生了几个问题 画布无限大, ...

  6. android自定义控件(6)-详解在onMeasure()方法中如何测量一个控件尺寸

    今天的任务就是详细研究一下protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)方法.如果只是说要重写什么方法有什么 ...

  7. Android中使用ListView绘制自定义表格(2)

    上回再写了<Android中使用ListView绘制自定义表格>后,很多人留言代码不全和没有数据样例.但因为项目原因,没法把源码全部贴上来.近两天,抽空简化了一下,做了一个例子. 效果图如 ...

  8. 【转】Android中引入第三方Jar包的方法(java.lang.NoClassDefFoundError解决办法)

    原文网址:http://www.blogjava.net/anchor110/articles/355699.html 1.在工程下新建lib文件夹,将需要的第三方包拷贝进来.2.将引用的第三方包,添 ...

  9. Android中解析XML格式数据的方法

    XML介绍:Extensible Markup Language,即可扩展标记语言 一.概述 Android中解析XML格式数据大致有三种方法: SAX DOM PULL 二.详解 2.1 SAX S ...

随机推荐

  1. 分享一个Jquery 分页插件 Jquery Pagination

    分页插件来说,我觉得适用就行,尽量简单然后能够根据不同的应用场景能够换肤.展现形式等. 对于初学者想写分页插件的同学,也可以看下源码,代码也挺简单明了的,也助于自己写个小插件. 不过我比较懒,一般直接 ...

  2. js基础-表单验证和提交

    基础知识: 原始提交如下: <form action="/login" method="post" id="form1"> &l ...

  3. 索引深入浅出(5/10):非聚集索引的B树结构在堆表

    在“索引深入浅出:非聚集索引的B树结构在聚集表”里,我们讨论了在聚集表上的非聚集索引,这篇文章我们讨论下在堆表上的非聚集索引. 非聚集索引可以在聚集表或堆表上创建.当我们在聚集表上创建非聚集索引时,聚 ...

  4. 问题:Virtual Box如何复制镜像

    今天遇到的情况就是vagrant启动的默认Virtalbox镜像变了,大致可以处理的方法是 1 修改vagrant的默认virtalbox 2 重新在这个新的virtualbox中安装需要的软件 3 ...

  5. Laravel4中的Validator

    不管写接口还是写web页面,实质都是传入参数,然后进行业务逻辑,然后再输出具体内容.所以,对参数的验证是不可避免的一个环节,比如传过来的email是不是为空,是不是合法的email格式?laravel ...

  6. mysql基于init-connect+binlog完成审计功能

    目前社区版本的mysql的审计功能还是比较弱的,基于插件的审计目前存在于Mysql的企业版.Percona和MariaDB上,但是mysql社区版本有提供init-connect选项,基于此我们可以用 ...

  7. web前端学习笔记---实现雪花飘落的效果

    看了javascript网页特效实例大全中的图片飘下的效果实例,觉得值得动手学习下. 就把图片改成雪花图,完成一个雪花飘下的效果. 并且,其中有些内容比较陈旧了,那么就学者改掉吧. 包括: 1.对le ...

  8. 检索 COM 类工厂中 CLSID 为 {28E68F9A-8D75-11D1-8DC3-3C302A000000} 的组件失败,原因是出现以下错误: 80040154 没有注册类 (异常来自 HRESULT:0x80040154 (REGDB_E_CLASSNOTREG))

    Resvr32 .net中引用控件的名称 如果注册成功,问题不在出现 但是如果是在x64位的系统中,即使控件注册成功,错误依照提示,是因为大多数第三方写的COM控件,只支持32位的系统, 在VS中找到 ...

  9. 用webBrowser打开网页出现脚本错误怎么办

    当IE浏览器遇到脚本错误时,在浏览器左下角会出现一个黄色图标,点击可以查看脚本错误的详细信息,并不会有弹出的错误信息框.我们在用webBrowser编写的程序打开网页,遇到脚本有问题是,会弹出一个错误 ...

  10. AlertDialog.Builder弹出对话框

    在Android中,弹出对话框使用AlertDialog.Builder方法. new AlertDialog.Builder(MainActivity.this).setTitle("本机 ...