分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow
也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!
本文主要介绍Android ViewGroup/View的绘制流程,及常用的自定义ViewGroup的方法。在此基础上介绍动态控制View的位置的三种方法,并给出最佳的一种方法。
一、ViewGroup/View的绘制流程
简单的说一个View从无到有需要三个步骤,onMeasure、onLayout、onDraw,即测量大小、放置位置、绘制三个步骤。而ViewGroup的onMeasure、onLayout流程里,又会遍历每个孩子,并最终调到孩子的measure()、layout()函数里。与View不同的是,ViewGroup没有onDraw流程,但有dispatchDraw()流程,该函数最终又调用drawChild()绘制每个孩子,调每个孩子View的onDraw流程。
在onMeasure流程里是为了获得控件的高和宽,这块有个getWidth()和getMeasuredWidth()的概念,前者指宽度,后者是测量宽度。一般来说,一个自定义VIewGroup(如继承自RelativeLayout)一般要进两次onMeasure,一次onLayout,一次drawChild()。虽然onMeasure流程是测量大小,且进了两次。但直到最后一次出去的时候调用getWidth()得到的仍然是0.getWidth()的数值一直到onSizeChanged()的时候才能够得到正确的,此后进到onLayout里当然也能正常得到。
下面是我截的一段代码:
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub Log.i(TAG, "onMeasure enter..."); Log.i(TAG, "width = " + getWidth() + " height = " + getHeight()); Log.i(TAG, "MeasuredWidth = " + getMeasuredWidth() + " MeasuredHeight = " + getMeasuredHeight()); super.onMeasure(widthMeasureSpec, heightMeasureSpec); Log.i(TAG, "00000000000 width = " + getWidth() + " height = " + getHeight()); Log.i(TAG, "00000000000 MeasuredWidth = " + getMeasuredWidth() + " MeasuredHeight = " + getMeasuredHeight()); Log.i(TAG, "onMeasure exit..."); }
打印信息:
Line 355: 01-03 10:15:40.526 I/YanZi (10793): onMeasure enter... Line 357: 01-03 10:15:40.526 I/YanZi (10793): width = 0 height = 0 Line 359: 01-03 10:15:40.527 I/YanZi (10793): MeasuredWidth = 0 MeasuredHeight = 0 Line 361: 01-03 10:15:40.531 I/YanZi (10793): 00000000000 width = 0 height = 0 Line 363: 01-03 10:15:40.532 I/YanZi (10793): 00000000000 MeasuredWidth = 1080 MeasuredHeight = 1701 Line 365: 01-03 10:15:40.532 I/YanZi (10793): onMeasure exit... Line 367: 01-03 10:15:40.532 I/YanZi (10793): onMeasure enter... Line 369: 01-03 10:15:40.533 I/YanZi (10793): width = 0 height = 0 Line 371: 01-03 10:15:40.533 I/YanZi (10793): MeasuredWidth = 1080 MeasuredHeight = 1701 Line 373: 01-03 10:15:40.536 I/YanZi (10793): 00000000000 width = 0 height = 0 Line 375: 01-03 10:15:40.536 I/YanZi (10793): 00000000000 MeasuredWidth = 1080 MeasuredHeight = 1701 Line 377: 01-03 10:15:40.537 I/YanZi (10793): onMeasure exit... Line 379: 01-03 10:15:40.537 I/YanZi (10793): onSizeChanged enter... Line 381: 01-03 10:15:40.538 I/YanZi (10793): width = 1080 height = 1701 Line 383: 01-03 10:15:40.538 I/YanZi (10793): onSizeChanged exit... Line 385: 01-03 10:15:40.538 I/YanZi (10793): onLayout enter... Line 387: 01-03 10:15:40.539 I/YanZi (10793): width = 1080 height = 1701 Line 389: 01-03