自定义控件其实很简单7/12

尊重原创转载请注明:From AigeStudio(http://blog.csdn.net/aigestudio)Power by Aige 侵权必究!

炮兵镇楼

要在数量上统计中国菜的品种,在地域上毫无争议地划分菜系,在今天,是一件几乎不可能完成的事……Cut…………抱歉……忘吃药了,再来一遍。如果非要对自定义控件的流程进行一个简单的划分,我会尝试将其分为三大部分:控件的绘制、控件的测量和控件的交互行为。前面我们用了六节的篇幅和一个翻页的例子来对控件的绘制有了一个全新的认识但是我们所做出的所有例子都是不完美的,为什么这么说呢,还是先来看个sample:

[java]  view plain copy print ?
  1. /** 
  2.  *  
  3.  * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  4.  * @since 2015/1/12 
  5.  *  
  6.  */  
  7. public class ImgView extends View {  
  8.     private Bitmap mBitmap;// 位图对象  
  9.   
  10.     public ImgView(Context context, AttributeSet attrs) {  
  11.         super(context, attrs);  
  12.     }  
  13.   
  14.     @Override  
  15.     protected void onDraw(Canvas canvas) {  
  16.         // 绘制位图  
  17.         canvas.drawBitmap(mBitmap, 00null);  
  18.     }  
  19.   
  20.     /** 
  21.      * 设置位图 
  22.      *  
  23.      * @param bitmap 
  24.      *            位图对象 
  25.      */  
  26.     public void setBitmap(Bitmap bitmap) {  
  27.         this.mBitmap = bitmap;  
  28.     }  
  29. }  
这个例子呢非常简单,我们用它来模拟类似ImageView的效果显示一张图片,在MainActivity中我们获取该控件并为其设置Bitmap:

[java]  view plain copy print ?
  1. /** 
  2.  * 主界面 
  3.  *  
  4.  * @author Aige {@link http://blog.csdn.net/aigestudio} 
  5.  * @since 2014/11/17 
  6.  */  
  7. public class MainActivity extends Activity {  
  8.     private ImgView mImgView;  
  9.   
  10.     @Override  
  11.     public void onCreate(Bundle savedInstanceState) {  
  12.         super.onCreate(savedInstanceState);  
  13.         setContentView(R.layout.activity_main);  
  14.   
  15.         mImgView = (ImgView) findViewById(R.id.main_pv);  
  16.         Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.lovestory);  
  17.         mImgView.setBitmap(bitmap);  
  18.     }  
  19. }  
此时运行效果如下:


很简单对吧,可是上面的代码其实是有个问题的,至于什么问题?我们待会再说,就看你通过前面我们的学习能不能发现了。这一节我们重点是控件的测量,大家不知道注意没有,这个系列文章的命名我用了“控件”而非“View”其实目的就是说明我们的控件不仅包括View也应该包含ViewGroup,当然你也可以以官方的方式将其分为控件和布局,不过我更喜欢View和ViewGroup,好了废话不说,我们先来看看View的测量方式,上面的代码中MainActivity对应的布局文件如下:

[html]  view plain copy print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FFFFFFFF"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.ImgView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" />  
  11. </LinearLayout>  
既然我们的自定义View也算一个控件那么我们也可以像平时做布局那样往我们的LinearLayout中添加各种各样的其他控件对吧:

[html]  view plain copy print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FFFFFFFF"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.ImgView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="match_parent"  
  10.         android:layout_height="match_parent" />  
  11.   
  12.     <Button  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:text="AigeStudio" />  
  16.   
  17.     <TextView  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content"  
  20.         android:text="AigeStudio" />  
  21.   
  22. </LinearLayout>  
但是运行后你却发现我们的Button和TextView却没有显示在屏幕上,这时你可能会说那当然咯,因为我们的ImgViewlayout_width和layout_height均为match_parent,可是即便你将其改成wrap_content:

[html]  view plain copy print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FFFFFFFF"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.ImgView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content" />  
  11.   
  12.     <!-- ……省略一些代码…… -->  
  13. </LinearLayout>  
结果也一样,这时你肯定很困惑,不解的主要原因是没有搞懂View的测量机制,在前面的几节中我们或多或少有提到控件的测量,也曾经说过Android提供给我们能够操纵控件测量的方法是onMeasure:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  4. }  
默认情况下onMeasure方法中只是简单地将签名列表中的两个int型参数回传给父类的onMeasure方法,然后由父类的方法去计算出最终的测量值。但是,这里有个问题非常重要,就是onMeasure签名列表中的这两个参数是从何而来,这里可以告诉大家的是,这两个参数是由view的父容器,代码中也就是我们的LinearLayout传递进来的,很多初学Android的朋友会将位于xml布局文件顶端的控件称之为根布局,比如这里我们的LinearLayout,而事实上在Android的GUI框架中,这个LinearLayout还称不上根布局,我们知道一个Activity可以对应一个View(也可以是ViewGroup),很多情况下我们会通过Activity的setContentView方法去设置我们的View:

[java]  view plain copy print ?
  1. @Override  
  2. public void onCreate(Bundle savedInstanceState) {  
  3.     super.onCreate(savedInstanceState);  
  4.     setContentView(R.layout.activity_main);  
  5. }  
setContentView在Activity内的实现也非常简单,就是调用getWindow方法获取一个Window类型的对象并调用其setContentView方法:

[java]  view plain copy print ?
  1. public void setContentView(int layoutResID) {  
  2.     getWindow().setContentView(layoutResID);  
  3.     initActionBar();  
  4. }  
而这个Window对象

[java]  view plain copy print ?
  1. public Window getWindow() {  
  2.     return mWindow;  
  3. }  
其本质也就是一个PhoneWindow,在Activity的attach方法中通过makeNewWindow生成:

[java]  view plain copy print ?
  1. final void attach(Context context, ActivityThread aThread,  
  2.     // 此处省去一些代码……  
  3.   
  4.     mWindow = PolicyManager.makeNewWindow(this);  
  5.     mWindow.setCallback(this);  
  6.     mWindow.getLayoutInflater().setPrivateFactory(this);  
  7.     if (info.softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {  
  8.         mWindow.setSoftInputMode(info.softInputMode);  
  9.     }  
  10.     if (info.uiOptions != 0) {  
  11.         mWindow.setUiOptions(info.uiOptions);  
  12.     }  
  13.       
  14.     // 此处省去巨量代码……  
  15. }  
在PolicyManager中通过反射的方式获取com.android.internal.policy.impl.Policy的一个实例:

[java]  view plain copy print ?
  1. public final class PolicyManager {  
  2.     private static final String POLICY_IMPL_CLASS_NAME =  
  3.         "com.android.internal.policy.impl.Policy";  
  4.   
  5.     private static final IPolicy sPolicy;  
  6.   
  7.     static {  
  8.         try {  
  9.             Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);  
  10.             sPolicy = (IPolicy)policyClass.newInstance();  
  11.         } catch (ClassNotFoundException ex) {  
  12.             throw new RuntimeException(  
  13.                     POLICY_IMPL_CLASS_NAME + " could not be loaded", ex);  
  14.         } catch (InstantiationException ex) {  
  15.             throw new RuntimeException(  
  16.                     POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);  
  17.         } catch (IllegalAccessException ex) {  
  18.             throw new RuntimeException(  
  19.                     POLICY_IMPL_CLASS_NAME + " could not be instantiated", ex);  
  20.         }  
  21.     }  
  22.   
  23.     // 省去构造方法……  
  24.   
  25.     public static Window makeNewWindow(Context context) {  
  26.         return sPolicy.makeNewWindow(context);  
  27.     }  
  28.   
  29.     // 省去无关代码……  
  30. }  
并通过其内部的makeNewWindow实现返回一个PhoneWindow对象:

[java]  view plain copy print ?
  1. public Window makeNewWindow(Context context) {  
  2.     return new PhoneWindow(context);  
  3. }  
PhoneWindow是Window的一个子类,其对Window中定义的大量抽象方法作了具体的实现,比如我们的setContentView方法在Window中仅做了一个抽象方法定义:

[java]  view plain copy print ?
  1. public abstract class Window {  
  2.     // 省去不可估量的代码……  
  3.   
  4.     public abstract void setContentView(int layoutResID);  
  5.   
  6.     public abstract void setContentView(View view);  
  7.   
  8.     public abstract void setContentView(View view, ViewGroup.LayoutParams params);  
  9.   
  10.     // 省去数以亿计的代码……  
  11. }  
其在PhoneWindow中都有具体的实现:

[java]  view plain copy print ?
  1. public class PhoneWindow extends Window implements MenuBuilder.Callback {  
  2.     // 省去草泥马个代码……  
  3.   
  4.     @Override  
  5.     public void setContentView(int layoutResID) {  
  6.         if (mContentParent == null) {  
  7.             installDecor();  
  8.         } else {  
  9.             mContentParent.removeAllViews();  
  10.         }  
  11.         mLayoutInflater.inflate(layoutResID, mContentParent);  
  12.         final Callback cb = getCallback();  
  13.         if (cb != null && !isDestroyed()) {  
  14.             cb.onContentChanged();  
  15.         }  
  16.     }  
  17.   
  18.     @Override  
  19.     public void setContentView(View view) {  
  20.         setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));  
  21.     }  
  22.   
  23.     @Override  
  24.     public void setContentView(View view, ViewGroup.LayoutParams params) {  
  25.         if (mContentParent == null) {  
  26.             installDecor();  
  27.         } else {  
  28.             mContentParent.removeAllViews();  
  29.         }  
  30.         mContentParent.addView(view, params);  
  31.         final Callback cb = getCallback();  
  32.         if (cb != null && !isDestroyed()) {  
  33.             cb.onContentChanged();  
  34.         }  
  35.     }  
  36.   
  37.     // 省去法克鱿个代码……  
  38. }  
当然如果你要是使用了TV的SDK那么这里就不是PhoneWindow而是TVWindow了,至于是不是呢?留给大家去验证。到这里我们都还没完,在PhoneWindow的setContentView方法中先会去判断mContentParent这个引用是否为空,如果为空则表示我们是第一次生成那么调用installDecor方法去生成一些具体的对象否则清空该mContentParent下的所有子元素(注意mContentParent是一个ViewGroup)并通过LayoutInflater将xml布局转换为View Tree添加至mContentParent中(这里根据setContentView(int layoutResID)方法分析,其他重载方法类似),installDecor方法做的事相对多但不复杂,首先是对DecorView类型的mDecor成员变量赋值继而将其注入generateLayout方法生成我们的mContentParent:

[java]  view plain copy print ?
  1. private void installDecor() {  
  2.     if (mDecor == null) {  
  3.         mDecor = generateDecor();  
  4.         //  省省省……  
  5.     }  
  6.   
  7.     if (mContentParent == null) {  
  8.         mContentParent = generateLayout(mDecor);  
  9.   
  10.         //  省省省……  
  11.     }  
  12.   
  13.     //  省省省……  
  14. }  
generateLayout方法中做的事就多了,简直可以跟performTraversals拼,这里不贴代码了简单分析一下,generateLayout方法中主要根据当前我们的Style类型为当前Window选择不同的布局文件,看到这里,想必大家也该意识到,这才是我们的“根布局”,其会指定一个用来存放我们自定义布局文件(也就是我们口头上常说的根布局比如我们例子中的LinearLayout)的ViewGroup,一般情况下这个ViewGroup的重任由FrameLayout来承担,这也是为什么我们在获取我们xml布局文件中的顶层布局时调用其getParent()方法会返回FrameLayout对象的原因,其id为android:id="@android:id/content":

[java]  view plain copy print ?
  1. protected ViewGroup generateLayout(DecorView decor) {  
  2.     // 省去巨量代码……  
  3.   
  4.     ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);  
  5.   
  6.     // 省去一些代码……  
  7. }  
在这个Window布局文件被确定后,mDecor则会将该布局所生成的对应View添加进来并获取id为content的View将其赋给mContentParent,至此mContentParent和mDecor均已生成,而我们xml布局文件中的布局则会被添加至mContentParent。对应关系类似下图:


说了大半天才理清这个小关系,但是我们还没说到重点…………………………就是widthMeasureSpec和heightMeasureSpec究竟是从哪来的……………………如果我们不做上面的一个分析,很多童鞋压根无从下手,有了上面一个分析,我们知道我们界面的真正根视图应该是DecorView,那么我们的widthMeasureSpec和heightMeasureSpec应该从这里或者更上一层PhoneWindow传递进来对吧,但是DecorView是FrameLayout的一个实例,在FrameLayout的onMeasure中我们确实有对子元素的测量,但是问题是FrameLayout:onMeasure方法中的widthMeasureSpec和heightMeasureSpec又是从何而来呢?追溯上去我们又回到了View…………………………………………………………不了解Android GUI框架的童鞋迈出的第一步就被无情地煽了回去。其实在Android中我们可以在很多方面看到类似MVC架构的影子,比如最最常见的就是我们的xml界面布局——Activity等组件——model数据之间的关系,而在整个GUI的框架中,我们也可以对其做出类似的规划,View在设计过程中就注定了其只会对显示数据进行处理比如我们的测量布局和绘制还有动画等等,而承担Controller控制器重任的是谁呢?在Android中这一功能由ViewRootImpl承担,我们在前面提到过这个类,其负责的东西很多,比如我们窗口的显示、用户的输入输出当然还有关于处理我们绘制流程的方法:

[java]  view plain copy print ?
  1. private void performTraversals() {  
  2.     // ………………啦啦啦啦………………  
  3. }  
performTraversals方法是处理绘制流程的一个开始,内部逻辑相当相当多&复杂,虽然没有View类复杂……但是让我选的话我宁愿看整个View类也不愿看performTraversals方法那邪恶的逻辑…………囧,在该方法中我们可以看到如下的一段逻辑(具体各类变量的赋值就不贴了实在太多):

[java]  view plain copy print ?
  1. private void performTraversals() {  
  2.     // ………省略宇宙尘埃数量那么多的代码………  
  3.   
  4.     if (!mStopped) {  
  5.         // ……省略一些代码  
  6.   
  7.         int childWidthMeasureSpec = getRootMeasureSpec(mWidth, lp.width);  
  8.         int childHeightMeasureSpec = getRootMeasureSpec(mHeight, lp.height);  
  9.   
  10.         // ……省省省  
  11.   
  12.         performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);  
  13.     }  
  14.   
  15.     // ………省略人体细胞数量那么多的代码………  
  16. }  
可以看到在performTraversals方法中通过getRootMeasureSpec获取原始的测量规格并将其作为参数传递给performMeasure方法处理,这里我们重点来看getRootMeasureSpec方法是如何确定测量规格的,首先我们要知道mWidth, lp.width和mHeight, lp.height这两组参数的意义,其中lp.width和lp.height均为MATCH_PARENT,其在mWindowAttributes(WindowManager.LayoutParams类型)将值赋予给lp时就已被确定,mWidth和mHeight表示当前窗口的大小,其值由performTraversals中一系列逻辑计算确定,这里跳过,而在getRootMeasureSpec中作了如下判断:

[java]  view plain copy print ?
  1. private static int getRootMeasureSpec(int windowSize, int rootDimension) {  
  2.     int measureSpec;  
  3.     switch (rootDimension) {  
  4.   
  5.     case ViewGroup.LayoutParams.MATCH_PARENT:  
  6.         // Window不能调整其大小,强制使根视图大小与Window一致  
  7.         measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);  
  8.         break;  
  9.     case ViewGroup.LayoutParams.WRAP_CONTENT:  
  10.         // Window可以调整其大小,为根视图设置一个最大值  
  11.         measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);  
  12.         break;  
  13.     default:  
  14.         // Window想要一个确定的尺寸,强制将根视图的尺寸作为其尺寸  
  15.         measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);  
  16.         break;  
  17.     }  
  18.     return measureSpec;  
  19. }  
也就是说不管如何,我们的根视图大小必定都是全屏的……

至此,我们算是真正接触到根视图的测量规格,尔后这个规格会被由上至下传递下去,并由当前view与其父容器共同作用决定最终的测量大小,在View与ViewGroup递归调用实现测量的过程中有几个重要的方法,对于View而言则是measure方法:

[java]  view plain copy print ?
  1. public final void measure(int widthMeasureSpec, int heightMeasureSpec) {  
  2.     // 省略部分代码……  
  3.   
  4.     /* 
  5.      * 判断当前mPrivateFlags是否带有PFLAG_FORCE_LAYOUT强制布局标记 
  6.      * 判断当前widthMeasureSpec和heightMeasureSpec是否发生了改变 
  7.      */  
  8.     if ((mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ||  
  9.             widthMeasureSpec != mOldWidthMeasureSpec ||  
  10.             heightMeasureSpec != mOldHeightMeasureSpec) {  
  11.   
  12.         // 如果发生了改变表示需要重新进行测量此时清除掉mPrivateFlags中已测量的标识位PFLAG_MEASURED_DIMENSION_SET  
  13.         mPrivateFlags &= ~PFLAG_MEASURED_DIMENSION_SET;  
  14.   
  15.         resolveRtlPropertiesIfNeeded();  
  16.   
  17.         int cacheIndex = (mPrivateFlags & PFLAG_FORCE_LAYOUT) == PFLAG_FORCE_LAYOUT ? -1 :  
  18.                 mMeasureCache.indexOfKey(key);  
  19.         if (cacheIndex < 0 || sIgnoreMeasureCache) {  
  20.             // 测量View的尺寸  
  21.             onMeasure(widthMeasureSpec, heightMeasureSpec);  
  22.             mPrivateFlags3 &= ~PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;  
  23.         } else {  
  24.             long value = mMeasureCache.valueAt(cacheIndex);  
  25.   
  26.             setMeasuredDimension((int) (value >> 32), (int) value);  
  27.             mPrivateFlags3 |= PFLAG3_MEASURE_NEEDED_BEFORE_LAYOUT;  
  28.         }  
  29.   
  30.         /* 
  31.          * 如果mPrivateFlags里没有表示已测量的标识位PFLAG_MEASURED_DIMENSION_SET则会抛出异常 
  32.          */  
  33.         if ((mPrivateFlags & PFLAG_MEASURED_DIMENSION_SET) != PFLAG_MEASURED_DIMENSION_SET) {  
  34.             throw new IllegalStateException("onMeasure() did not set the"  
  35.                     + " measured dimension by calling"  
  36.                     + " setMeasuredDimension()");  
  37.         }  
  38.   
  39.         // 如果已测量View那么就可以往mPrivateFlags添加标识位PFLAG_LAYOUT_REQUIRED表示可以进行布局了  
  40.         mPrivateFlags |= PFLAG_LAYOUT_REQUIRED;  
  41.     }  
  42.   
  43.     // 最后存储测量完成的测量规格  
  44.     mOldWidthMeasureSpec = widthMeasureSpec;  
  45.     mOldHeightMeasureSpec = heightMeasureSpec;  
  46.   
  47.     mMeasureCache.put(key, ((long) mMeasuredWidth) << 32 |  
  48.             (long) mMeasuredHeight & 0xffffffffL); // suppress sign extension  
  49. }  
可以看到,View对控件的测量是在onMeasure方法中进行的,也就是文章开头我们在自定义View中重写的onMeasure方法,但是我们并没有对其做任何的处理,也就是说保持了其在父类View中的默认实现,其默认实现也很简单:

[java]  view plain copy print ?
  1. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  2.     setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),  
  3.             getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));  
  4. }  
其直接调用了setMeasuredDimension方法为其设置了两个计算后的测量值:

[java]  view plain copy print ?
  1. protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {  
  2.     // 省去部分代码……  
  3.   
  4.     // 设置测量后的宽高  
  5.     mMeasuredWidth = measuredWidth;  
  6.     mMeasuredHeight = measuredHeight;  
  7.   
  8.     // 重新将已测量标识位存入mPrivateFlags标识测量的完成  
  9.     mPrivateFlags |= PFLAG_MEASURED_DIMENSION_SET;  
  10. }  
回到onMeasure方法,我们来看看这两个测量值具体是怎么获得的,其实非常简单,首先来看getSuggestedMinimumWidth方法:

[java]  view plain copy print ?
  1. protected int getSuggestedMinimumWidth() {  
  2.     return (mBackground == null) ? mMinWidth : max(mMinWidth, mBackground.getMinimumWidth());  
  3. }  
如果背景为空那么我们直接返回mMinWidth最小宽度否则就在mMinWidth和背景最小宽度之间取一个最大值,getSuggestedMinimumHeight类同,mMinWidth和mMinHeight我没记错的话应该都是100px,而getDefaultSize方法呢也很简单:

[java]  view plain copy print ?
  1. public static int getDefaultSize(int size, int measureSpec) {  
  2.     // 将我们获得的最小值赋给result  
  3.     int result = size;  
  4.   
  5.     // 从measureSpec中解算出测量规格的模式和尺寸  
  6.     int specMode = MeasureSpec.getMode(measureSpec);  
  7.     int specSize = MeasureSpec.getSize(measureSpec);  
  8.   
  9.     /* 
  10.      * 根据测量规格模式确定最终的测量尺寸 
  11.      */  
  12.     switch (specMode) {  
  13.     case MeasureSpec.UNSPECIFIED:  
  14.         result = size;  
  15.         break;  
  16.     case MeasureSpec.AT_MOST:  
  17.     case MeasureSpec.EXACTLY:  
  18.         result = specSize;  
  19.         break;  
  20.     }  
  21.     return result;  
  22. }  
注意上述代码中当模式为AT_MOST和EXACTLY时均会返回解算出的测量尺寸,还记得上面我们说的PhoneWindow、DecorView么从它们那里获取到的测量规格层层传递到我们的自定义View中,这就是为什么我们的View在默认情况下不管是math_parent还是warp_content都能占满父容器的剩余空间(这里面还有父布局LinearLayout的作用就先略过了了解即可)。上述onMeasure的过程则是View默认的处理过程,如果我们不喜欢Android帮我们处理那么我们可以自己重写onMeasure实现自己的测量逻辑:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     // 设置测量尺寸  
  4.     setMeasuredDimension(250250);  
  5. }  
最简单的粗暴的就是直接将两个值作为参数传入setMeasuredDimension方法,效果如下:


当然这样不好,用Android官方的话来说就是太过“专政”,因为它完全摒弃了父容器的意愿,完全由自己决定了大小,如果大家逛blog看技术文章或者听别人讨论常常会听到别人这么说view的最终测量尺寸是由view本身何其父容器共同决定的,至于如何共同决定我们呆会再说,这里我们先看看如何能在一定程度上顺应爹的“意愿”呢?从View默认的测量模式中我们可以看到它频繁使用了一个叫做MeasureSpec的类,而在ViewRootImpl中呢也有大量用到该类,该类的具体说明大家可以围观我早期的一篇文章:http://blog.csdn.net/aigestudio/article/details/38636531,里面有对MeasureSpec类的详细说明,这里我就简单概述下MeasureSpec类中的三个Mode常量值的意义,其中UNSPECIFIED表示未指定,爹不会对儿子作任何的束缚,儿子想要多大都可以;EXACTLY表示完全的,意为儿子多大爹心里有数,爹早已算好了;AT_MOST表示至多,爹已经为儿子设置好了一个最大限制,儿子你不能比这个值大,不能再多了!父容器所谓的“意图”其实就由上述三个常量值表现,既然如此我们就该对这三个Mode常量做一个判断才行,不然怎么知道爹的意图呢:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     // 声明一个临时变量来存储计算出的测量值  
  4.     int resultWidth = 0;  
  5.   
  6.     // 获取宽度测量规格中的mode  
  7.     int modeWidth = MeasureSpec.getMode(widthMeasureSpec);  
  8.   
  9.     // 获取宽度测量规格中的size  
  10.     int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);  
  11.   
  12.     /* 
  13.      * 如果爹心里有数 
  14.      */  
  15.     if (modeWidth == MeasureSpec.EXACTLY) {  
  16.         // 那么儿子也不要让爹难做就取爹给的大小吧  
  17.         resultWidth = sizeWidth;  
  18.     }  
  19.     /* 
  20.      * 如果爹心里没数 
  21.      */  
  22.     else {  
  23.         // 那么儿子可要自己看看自己需要多大了  
  24.         resultWidth = mBitmap.getWidth();  
  25.   
  26.         /* 
  27.          * 如果爹给儿子的是一个限制值 
  28.          */  
  29.         if (modeWidth == MeasureSpec.AT_MOST) {  
  30.             // 那么儿子自己的需求就要跟爹的限制比比看谁小要谁  
  31.             resultWidth = Math.min(resultWidth, sizeWidth);  
  32.         }  
  33.     }  
  34.   
  35.     int resultHeight = 0;  
  36.     int modeHeight = MeasureSpec.getMode(heightMeasureSpec);  
  37.     int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);  
  38.   
  39.     if (modeHeight == MeasureSpec.EXACTLY) {  
  40.         resultHeight = sizeHeight;  
  41.     } else {  
  42.         resultHeight = mBitmap.getHeight();  
  43.         if (modeHeight == MeasureSpec.AT_MOST) {  
  44.             resultHeight = Math.min(resultHeight, sizeHeight);  
  45.         }  
  46.     }  
  47.   
  48.     // 设置测量尺寸  
  49.     setMeasuredDimension(resultWidth, resultHeight);  
  50. }  
如上代码所示我们从父容器传来的MeasureSpec中分离出了mode和size,size只是一个期望值我们需要根据mode来计算最终的size,如果父容器对子元素没有一个确切的大小那么我们就需要尝试去计算子元素也就是我们的自定义View的大小,而这部分大小更多的是由我们也就是开发者去根据实际情况计算的,这里我们模拟的是一个显示图片的控件,那么控件的实际大小就应该跟我们的图片一致,但是虽然我们可以做出一定的决定也要考虑父容器的限制值,当mode为AT_MOST时size则是父容器给予我们的一个最大值,我们控件的大小就不应该超过这个值。下面是运行效果:


如我所说,控件的实际大小需要根据我们的实际需求去计算,这里我更改一下xml为我们的ImgView加一个内边距值:

[html]  view plain copy print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FFFFFFFF"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.ImgView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:padding="20dp" />  
  12.   
  13.     <Button  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="AigeStudio" />  
  17.   
  18.     <TextView  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:text="AigeStudio" />  
  22.   
  23. </LinearLayout>  
这时你会发现蛋疼了……毫无内边距的效果,而在这种情况下我们则需在计算控件尺寸时考虑内边距的大小:

[java]  view plain copy print ?
  1. resultWidth = mBitmap.getWidth() + getPaddingLeft() + getPaddingRight();  
  2. resultHeight = mBitmap.getHeight() + getPaddingTop() + getPaddingBottom();  
这时我们就有了内边距的效果对吧:


诶、等等,好像不对啊,上边距和左边距为什么没有了?原因很简单,因为我们在绘制时并没有考虑到Padding的影响,下面我们更改一下绘制逻辑:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onDraw(Canvas canvas) {  
  3.     // 绘制位图  
  4.     canvas.drawBitmap(mBitmap, getPaddingLeft(), getPaddingTop(), null);  
  5. }  
这时我们的内边距就完美了:


很多朋友问那Margin外边距呢??淡定,外边距轮不到view来算,Andorid将其封装在LayoutParams内交由父容器统一处理。很多时候我们的控件往往不只是一张简单的图片那么乏味,比如类似图标的效果:


一个图标常常除了一张图片外底部还有一个title,这时我们的测量逻辑就应该做出相应的改变了,这里我用一个新的IconView去做:

[java]  view plain copy print ?
  1. /** 
  2.  *  
  3.  * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  4.  * @since 2015/1/13 
  5.  *  
  6.  */  
  7. public class IconView extends View {  
  8.     private Bitmap mBitmap;// 位图  
  9.     private TextPaint mPaint;// 绘制文本的画笔  
  10.     private String mStr;// 绘制的文本  
  11.   
  12.     private float mTextSize;// 画笔的文本尺寸  
  13.   
  14.     /** 
  15.      * 宽高枚举类 
  16.      *  
  17.      * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  18.      *  
  19.      */  
  20.     private enum Ratio {  
  21.         WIDTH, HEIGHT  
  22.     }  
  23.   
  24.     public IconView(Context context, AttributeSet attrs) {  
  25.         super(context, attrs);  
  26.   
  27.         // 计算参数  
  28.         calArgs(context);  
  29.   
  30.         // 初始化  
  31.         init();  
  32.     }  
  33.   
  34.     /** 
  35.      * 参数计算 
  36.      *  
  37.      * @param context 
  38.      *            上下文环境引用 
  39.      */  
  40.     private void calArgs(Context context) {  
  41.         // 获取屏幕宽  
  42.         int sreenW = MeasureUtil.getScreenSize((Activity) context)[0];  
  43.   
  44.         // 计算文本尺寸  
  45.         mTextSize = sreenW * 1 / 10F;  
  46.     }  
  47.   
  48.     /** 
  49.      * 初始化 
  50.      */  
  51.     private void init() {  
  52.         /* 
  53.          * 获取Bitmap 
  54.          */  
  55.         if (null == mBitmap) {  
  56.             mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo);  
  57.         }  
  58.   
  59.         /* 
  60.          * 为mStr赋值 
  61.          */  
  62.         if (null == mStr || mStr.trim().length() == 0) {  
  63.             mStr = "AigeStudio";  
  64.         }  
  65.   
  66.         /* 
  67.          * 初始化画笔并设置参数 
  68.          */  
  69.         mPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.LINEAR_TEXT_FLAG);  
  70.         mPaint.setColor(Color.LTGRAY);  
  71.         mPaint.setTextSize(mTextSize);  
  72.         mPaint.setTextAlign(Paint.Align.CENTER);  
  73.         mPaint.setTypeface(Typeface.DEFAULT_BOLD);  
  74.     }  
  75.   
  76.     @Override  
  77.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  78.         // 设置测量后的尺寸  
  79.         setMeasuredDimension(getMeasureSize(widthMeasureSpec, Ratio.WIDTH), getMeasureSize(heightMeasureSpec, Ratio.HEIGHT));  
  80.     }  
  81.   
  82.     /** 
  83.      * 获取测量后的尺寸 
  84.      *  
  85.      * @param measureSpec 
  86.      *            测量规格 
  87.      * @param ratio 
  88.      *            宽高标识 
  89.      * @return 宽或高的测量值 
  90.      */  
  91.     private int getMeasureSize(int measureSpec, Ratio ratio) {  
  92.         // 声明临时变量保存测量值  
  93.         int result = 0;  
  94.   
  95.         /* 
  96.          * 获取mode和size 
  97.          */  
  98.         int mode = MeasureSpec.getMode(measureSpec);  
  99.         int size = MeasureSpec.getSize(measureSpec);  
  100.   
  101.         /* 
  102.          * 判断mode的具体值 
  103.          */  
  104.         switch (mode) {  
  105.         case MeasureSpec.EXACTLY:// EXACTLY时直接赋值  
  106.             result = size;  
  107.             break;  
  108.         default:// 默认情况下将UNSPECIFIED和AT_MOST一并处理  
  109.             if (ratio == Ratio.WIDTH) {  
  110.                 float textWidth = mPaint.measureText(mStr);  
  111.                 result = ((int) (textWidth >= mBitmap.getWidth() ? textWidth : mBitmap.getWidth())) + getPaddingLeft() + getPaddingRight();  
  112.             } else if (ratio == Ratio.HEIGHT) {  
  113.                 result = ((int) ((mPaint.descent() - mPaint.ascent()) * 2 + mBitmap.getHeight())) + getPaddingTop() + getPaddingBottom();  
  114.             }  
  115.   
  116.             /* 
  117.              * AT_MOST时判断size和result的大小取小值 
  118.              */  
  119.             if (mode == MeasureSpec.AT_MOST) {  
  120.                 result = Math.min(result, size);  
  121.             }  
  122.             break;  
  123.         }  
  124.         return result;  
  125.     }  
  126.   
  127.     @Override  
  128.     protected void onDraw(Canvas canvas) {  
  129.         /* 
  130.          * 绘制 
  131.          * 参数就不做单独处理了因为只会Draw一次不会频繁调用 
  132.          */  
  133.         canvas.drawBitmap(mBitmap, getWidth() / 2 - mBitmap.getWidth() / 2, getHeight() / 2 - mBitmap.getHeight() / 2null);  
  134.         canvas.drawText(mStr, getWidth() / 2, mBitmap.getHeight() + getHeight() / 2 - mBitmap.getHeight() / 2 - mPaint.ascent(), mPaint);  
  135.     }  
  136. }  
在xml文件中对其引用并加入一些系统自带的控件:

[html]  view plain copy print ?
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FFFFFFFF"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.IconView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:padding="50dp" />  
  12.   
  13.     <Button  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="AigeStudio" />  
  17.   
  18.     <TextView  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:text="AigeStudio" />  
  22.   
  23. </LinearLayout>  
效果如下:


好了就先这样吧,上面我们曾说过View的测量大小是由View和其父容器共同决定的,但是上述源码的分析中我们其实并没有体现,因为它们都在ViewGroup中,这里我们就要涉及ViewGroup中与测量相关的另外几个方法:measureChildren、measureChild和measureChildWithMargins还有getChildMeasureSpec,见名知意这几个方法都跟ViewGroup测量子元素有关,其中measureChildWithMargins和measureChildren类似只是加入了对Margins外边距的处理,ViewGroup提供对子元素测量的方法从measureChildren开始:

[java]  view plain copy print ?
  1. protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {  
  2.     final int size = mChildrenCount;  
  3.     final View[] children = mChildren;  
  4.     for (int i = 0; i < size; ++i) {  
  5.         final View child = children[i];  
  6.         if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {  
  7.             measureChild(child, widthMeasureSpec, heightMeasureSpec);  
  8.         }  
  9.     }  
  10. }  
measureChildren的逻辑很简单,通过父容器传入的widthMeasureSpec和heightMeasureSpec遍历子元素并调用measureChild方法去测量每一个子元素的宽高:

[java]  view plain copy print ?
  1. protected void measureChild(View child, int parentWidthMeasureSpec,  
  2.         int parentHeightMeasureSpec) {  
  3.     // 获取子元素的布局参数  
  4.     final LayoutParams lp = child.getLayoutParams();  
  5.   
  6.     /* 
  7.      * 将父容器的测量规格已经上下和左右的边距还有子元素本身的布局参数传入getChildMeasureSpec方法计算最终测量规格 
  8.      */  
  9.     final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,  
  10.             mPaddingLeft + mPaddingRight, lp.width);  
  11.     final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,  
  12.             mPaddingTop + mPaddingBottom, lp.height);  
  13.   
  14.     // 调用子元素的measure传入计算好的测量规格  
  15.     child.measure(childWidthMeasureSpec, childHeightMeasureSpec);  
  16. }  
这里我们主要就是看看getChildMeasureSpec方法是如何确定最终测量规格的:

[java]  view plain copy print ?
  1. public static int getChildMeasureSpec(int spec, int padding, int childDimension) {  
  2.     // 获取父容器的测量模式和尺寸大小  
  3.     int specMode = MeasureSpec.getMode(spec);  
  4.     int specSize = MeasureSpec.getSize(spec);  
  5.   
  6.     // 这个尺寸应该减去内边距的值  
  7.     int size = Math.max(0, specSize - padding);  
  8.   
  9.     // 声明临时变量存值  
  10.     int resultSize = 0;  
  11.     int resultMode = 0;  
  12.   
  13.     /* 
  14.      * 根据模式判断 
  15.      */  
  16.     switch (specMode) {  
  17.     case MeasureSpec.EXACTLY: // 父容器尺寸大小是一个确定的值  
  18.         /* 
  19.          * 根据子元素的布局参数判断 
  20.          */  
  21.         if (childDimension >= 0) { //如果childDimension是一个具体的值  
  22.             // 那么就将该值作为结果  
  23.             resultSize = childDimension;  
  24.   
  25.             // 而这个值也是被确定的  
  26.             resultMode = MeasureSpec.EXACTLY;  
  27.         } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果子元素的布局参数为MATCH_PARENT  
  28.             // 那么就将父容器的大小作为结果  
  29.             resultSize = size;  
  30.   
  31.             // 因为父容器的大小是被确定的所以子元素大小也是可以被确定的  
  32.             resultMode = MeasureSpec.EXACTLY;  
  33.         } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果子元素的布局参数为WRAP_CONTENT  
  34.             // 那么就将父容器的大小作为结果  
  35.             resultSize = size;  
  36.   
  37.             // 但是子元素的大小包裹了其内容后不能超过父容器  
  38.             resultMode = MeasureSpec.AT_MOST;  
  39.         }  
  40.         break;  
  41.   
  42.     case MeasureSpec.AT_MOST: // 父容器尺寸大小拥有一个限制值  
  43.         /* 
  44.          * 根据子元素的布局参数判断 
  45.          */  
  46.         if (childDimension >= 0) { //如果childDimension是一个具体的值  
  47.             // 那么就将该值作为结果  
  48.             resultSize = childDimension;  
  49.   
  50.             // 而这个值也是被确定的  
  51.             resultMode = MeasureSpec.EXACTLY;  
  52.         } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果子元素的布局参数为MATCH_PARENT  
  53.             // 那么就将父容器的大小作为结果  
  54.             resultSize = size;  
  55.   
  56.             // 因为父容器的大小是受到限制值的限制所以子元素的大小也应该受到父容器的限制  
  57.             resultMode = MeasureSpec.AT_MOST;  
  58.         } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果子元素的布局参数为WRAP_CONTENT  
  59.             // 那么就将父容器的大小作为结果  
  60.             resultSize = size;  
  61.   
  62.             // 但是子元素的大小包裹了其内容后不能超过父容器  
  63.             resultMode = MeasureSpec.AT_MOST;  
  64.         }  
  65.         break;  
  66.   
  67.     case MeasureSpec.UNSPECIFIED: // 父容器尺寸大小未受限制  
  68.         /* 
  69.          * 根据子元素的布局参数判断 
  70.          */  
  71.         if (childDimension >= 0) { //如果childDimension是一个具体的值  
  72.             // 那么就将该值作为结果  
  73.             resultSize = childDimension;  
  74.   
  75.             // 而这个值也是被确定的  
  76.             resultMode = MeasureSpec.EXACTLY;  
  77.         } else if (childDimension == LayoutParams.MATCH_PARENT) { //如果子元素的布局参数为MATCH_PARENT  
  78.             // 因为父容器的大小不受限制而对子元素来说也可以是任意大小所以不指定也不限制子元素的大小  
  79.             resultSize = 0;  
  80.             resultMode = MeasureSpec.UNSPECIFIED;  
  81.         } else if (childDimension == LayoutParams.WRAP_CONTENT) { //如果子元素的布局参数为WRAP_CONTENT  
  82.             // 因为父容器的大小不受限制而对子元素来说也可以是任意大小所以不指定也不限制子元素的大小  
  83.             resultSize = 0;  
  84.             resultMode = MeasureSpec.UNSPECIFIED;  
  85.         }  
  86.         break;  
  87.     }  
  88.   
  89.     // 返回封装后的测量规格  
  90.     return MeasureSpec.makeMeasureSpec(resultSize, resultMode);  
  91. }  
至此我们可以看到一个View的大小由其父容器的测量规格MeasureSpec和View本身的布局参数LayoutParams共同决定,但是即便如此,最终封装的测量规格也是一个期望值,究竟有多大还是我们调用setMeasuredDimension方法设置的。上面的代码中有些朋友看了可能会有疑问为什么childDimension >= 0就表示一个确切值呢?原因很简单,因为在LayoutParams中MATCH_PARENT和WRAP_CONTENT均为负数、哈哈!!正是基于这点,Android巧妙地将实际值和相对的布局参数分离开来。那么我们该如何对ViewGroup进行测量呢?这里为了说明问题,我们自定义一个ViewGroup:

[java]  view plain copy print ?
  1. /** 
  2.  *  
  3.  * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  4.  * @since 2015/1/15 
  5.  *  
  6.  */  
  7. public class CustomLayout extends ViewGroup {  
  8.   
  9.     public CustomLayout(Context context, AttributeSet attrs) {  
  10.         super(context, attrs);  
  11.     }  
  12.   
  13.     @Override  
  14.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  15.   
  16.     }  
  17.   
  18. }  
ViewGroup中的onLayout方法是一个抽象方法,这意味着你在继承时必须实现,onLayout的目的是为了确定子元素在父容器中的位置,那么这个步骤理应该由父容器来决定而不是子元素,因此,我们可以猜到View中的onLayout方法应该是一个空实现:

[java]  view plain copy print ?
  1. public class View implements Drawable.Callback, KeyEvent.Callback,  
  2.         AccessibilityEventSource {  
  3.     // 省去无数代码………………  
  4.   
  5.     /** 
  6.      * Called from layout when this view should 
  7.      * assign a size and position to each of its children. 
  8.      * 
  9.      * Derived classes with children should override 
  10.      * this method and call layout on each of 
  11.      * their children. 
  12.      * @param changed This is a new size or position for this view 
  13.      * @param left Left position, relative to parent 
  14.      * @param top Top position, relative to parent 
  15.      * @param right Right position, relative to parent 
  16.      * @param bottom Bottom position, relative to parent 
  17.      */  
  18.     protected void onLayout(boolean changed, int left, int top, int right, int bottom) {  
  19.     }  
  20.   
  21.     // 省去无数代码………………  
  22. }  
与View不同的是,ViewGroup表示一个容器,其内可以包含多个元素,既可以是一个布局也可以是一个普通的控件,那么在对ViewGroup测量时我们也应该对这些子元素进行测量:

[java]  view plain copy print ?
  1. /** 
  2.  *  
  3.  * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  4.  * @since 2015/1/15 
  5.  *  
  6.  */  
  7. public class CustomLayout extends ViewGroup {  
  8.   
  9.     public CustomLayout(Context context, AttributeSet attrs) {  
  10.         super(context, attrs);  
  11.     }  
  12.   
  13.     @Override  
  14.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  15.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  16.   
  17.         /* 
  18.          * 如果有子元素 
  19.          */  
  20.         if (getChildCount() > 0) {  
  21.             // 那么对子元素进行测量  
  22.             measureChildren(widthMeasureSpec, heightMeasureSpec);  
  23.         }  
  24.     }  
  25.   
  26.     @Override  
  27.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  28.   
  29.     }  
  30.   
  31. }  
然后我们在xml布局文件中替换原来的LinearLayout使用我们自定义的布局:

[html]  view plain copy print ?
  1. <com.aigestudio.customviewdemo.views.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FFFFFFFF"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.IconView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:padding="50dp" />  
  12.   
  13.     <Button  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:text="AigeStudio" />  
  17.   
  18.     <TextView  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:text="AigeStudio" />  
  22.   
  23. </com.aigestudio.customviewdemo.views.CustomLayout>  
运行后你会发现没有任何东西显示,为什么呢?如上所说我们需要父容器告诉子元素它的出现位置,而这个过程由onLayout方法去实现,但是此时我们的onLayout方法什么都没有,子元素自然也不知道自己该往哪搁,自然就什么都没有咯……知道了原因我们就来实现onLayout的逻辑:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  3.   
  4.     /* 
  5.      * 如果有子元素 
  6.      */  
  7.     if (getChildCount() > 0) {  
  8.         // 那么遍历子元素并对其进行定位布局  
  9.         for (int i = 0; i < getChildCount(); i++) {  
  10.             View child = getChildAt(i);  
  11.             child.layout(00, getMeasuredWidth(), getMeasuredHeight());  
  12.         }  
  13.     }  
  14. }  
逻辑很简单,如果有子元素那么我们遍历这些子元素并调用其layout方法告诉它们自己该在的位置,这里我们就直接让所有的子元素都从父容器的[0, 0]点开始到[getMeasuredWidth(), getMeasuredHeight()]父容器的测量宽高结束,这么一来,所有的子元素应该都是填充了父容器的对吧:


看到屏幕上的巨大Button我不禁吸了一口屁!这样的布局太蛋疼,全被Button一个玩完了还搞毛,可不可以像LinearLayout那样挨个显示呢?答案是肯定的!我们来修改下onLayout的逻辑:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  3.   
  4.     /* 
  5.      * 如果有子元素 
  6.      */  
  7.     if (getChildCount() > 0) {  
  8.         // 声明一个临时变量存储高度倍增值  
  9.         int mutilHeight = 0;  
  10.   
  11.         // 那么遍历子元素并对其进行定位布局  
  12.         for (int i = 0; i < getChildCount(); i++) {  
  13.             // 获取一个子元素  
  14.             View child = getChildAt(i);  
  15.   
  16.             // 通知子元素进行布局  
  17.             child.layout(0, mutilHeight, child.getMeasuredWidth(), child.getMeasuredHeight() + mutilHeight);  
  18.   
  19.             // 改变高度倍增值  
  20.             mutilHeight += child.getMeasuredHeight();  
  21.         }  
  22.     }  
  23. }  
可以看到我们通过一个mutilHeight来存储高度倍增值,每一次子元素布局完后将当前mutilHeight与当前子元素的高度相加并在下一个子元素布局时在高度上加上mutilHeight,效果如下:


是不是和上面LinearLayout效果有点一样了?当然LinearLayout的布局逻辑远比我们的复杂得多,我们呢也只是对其进行一个简单的模拟而已。大家注意到ViewGroup的onLayout方法的签名列表中有五个参数,其中boolean changed表示是否与上一次位置不同,其具体值在View的layout方法中通过setFrame等方法确定:

[java]  view plain copy print ?
  1. public void layout(int l, int t, int r, int b) {  
  2.     // 省略一些代码……  
  3.   
  4.     boolean changed = isLayoutModeOptical(mParent) ?  
  5.             setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);  
  6.   
  7.     // 省略大量代码……  
  8. }  
而剩下的四个参数则表示当前View与父容器的相对距离,如下图:


好了,说到这里想必大家对ViewGroup的测量也有一定的了解了,但是这必定不是测量过程全部,如我上面所说,测量的具体过程因控件而异,上面我们曾因为给我们的自定义View加了内边距后修改了绘制的逻辑,因为我们需要在绘制时考虑内边距的影响,而我们的自定义ViewGroup呢?是不是也一样呢?这里我给其加入60dp的内边距:

[html]  view plain copy print ?
  1. <com.aigestudio.customviewdemo.views.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:padding="60dp"  
  5.     android:background="#FFFFFFFF"  
  6.     android:orientation="vertical" >  
  7.   
  8.     <com.aigestudio.customviewdemo.views.IconView  
  9.         android:id="@+id/main_pv"  
  10.         android:layout_width="wrap_content"  
  11.         android:layout_height="wrap_content"  
  12.         android:padding="50dp" />  
  13.   
  14.     <Button  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="AigeStudio" />  
  18.   
  19.     <TextView  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="AigeStudio" />  
  23.   
  24. </com.aigestudio.customviewdemo.views.CustomLayout>  
运行后效果如下:


内边距把我们的子元素给“吃”掉了,那么也就是说我们在对子元素进行定位时应该进一步考虑到父容器内边距的影响对吧,OK,我们重理onLayout的逻辑:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  3.     // 获取父容器内边距  
  4.     int parentPaddingLeft = getPaddingLeft();  
  5.     int parentPaddingTop = getPaddingTop();  
  6.   
  7.     /* 
  8.      * 如果有子元素 
  9.      */  
  10.     if (getChildCount() > 0) {  
  11.         // 声明一个临时变量存储高度倍增值  
  12.         int mutilHeight = 0;  
  13.   
  14.         // 那么遍历子元素并对其进行定位布局  
  15.         for (int i = 0; i < getChildCount(); i++) {  
  16.             // 获取一个子元素  
  17.             View child = getChildAt(i);  
  18.   
  19.             // 通知子元素进行布局  
  20.             // 此时考虑父容器内边距的影响  
  21.             child.layout(parentPaddingLeft, mutilHeight + parentPaddingTop, child.getMeasuredWidth() + parentPaddingLeft, child.getMeasuredHeight() + mutilHeight + parentPaddingTop);  
  22.   
  23.             // 改变高度倍增值  
  24.             mutilHeight += child.getMeasuredHeight();  
  25.         }  
  26.     }  
  27. }  
此时的效果如下:


既然内边距如此,那么Margins外边距呢?我们来看看,在xml布局文件中为我们的CustomLayout加一个margins:

[html]  view plain copy print ?
  1. <com.aigestudio.customviewdemo.views.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:layout_margin="30dp"  
  5.     android:padding="20dp"  
  6.     android:background="#FF597210"  
  7.     android:orientation="vertical" >  
  8.   
  9.     <com.aigestudio.customviewdemo.views.IconView  
  10.         android:id="@+id/main_pv"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content" />  
  13.   
  14.     <Button  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="AigeStudio" />  
  18.   
  19.     <TextView  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="AigeStudio" />  
  23.   
  24. </com.aigestudio.customviewdemo.views.CustomLayout>  
效果如下:


OK,目测没什么问题,可是当我们为子元素设置外边距时,问题就来了……不管你怎么设都不会有任何效果,原因很简单,我们上面也说了,Margins是由父容器来处理,而我们的CustomLayout中并没有对其做任何的处理,那么我们应该怎么做呢?首先要知道Margins封装在LayoutParams中,如果我们想实现自己对其的处理那么我们必然也有必要实现自己布局的LayoutParams:

[java]  view plain copy print ?
  1. /** 
  2.  *  
  3.  * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  4.  * @since 2015/1/15 
  5.  *  
  6.  */  
  7. public class CustomLayout extends ViewGroup {  
  8.     // 省略部分代码…………  
  9.   
  10.     /** 
  11.      *  
  12.      * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  13.      *  
  14.      */  
  15.     public static class CustomLayoutParams extends MarginLayoutParams {  
  16.   
  17.         public CustomLayoutParams(MarginLayoutParams source) {  
  18.             super(source);  
  19.         }  
  20.   
  21.         public CustomLayoutParams(android.view.ViewGroup.LayoutParams source) {  
  22.             super(source);  
  23.         }  
  24.   
  25.         public CustomLayoutParams(Context c, AttributeSet attrs) {  
  26.             super(c, attrs);  
  27.         }  
  28.   
  29.         public CustomLayoutParams(int width, int height) {  
  30.             super(width, height);  
  31.         }  
  32.     }  
  33. }  
我们在我们的CustomLayout中生成了一个静态内部类CustomLayoutParams,保持其默认的构造方法即可,这里我们什么也没做,当然你可以定义自己的一些属性或逻辑处理,因控件而异这里不多说了,后面慢慢会用到。然后在我们的CustomLayout中重写所有与LayoutParams相关的方法,返回我们自己的CustomLayoutParams:

[java]  view plain copy print ?
  1. /** 
  2.  *  
  3.  * @author AigeStudio {@link http://blog.csdn.net/aigestudio} 
  4.  * @since 2015/1/15 
  5.  *  
  6.  */  
  7. public class CustomLayout extends ViewGroup {  
  8.     // 省略部分代码…………  
  9.   
  10.     /** 
  11.      * 生成默认的布局参数 
  12.      */  
  13.     @Override  
  14.     protected CustomLayoutParams generateDefaultLayoutParams() {  
  15.         return new CustomLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);  
  16.     }  
  17.   
  18.     /** 
  19.      * 生成布局参数 
  20.      * 将布局参数包装成我们的 
  21.      */  
  22.     @Override  
  23.     protected android.view.ViewGroup.LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams p) {  
  24.         return new CustomLayoutParams(p);  
  25.     }  
  26.   
  27.     /** 
  28.      * 生成布局参数 
  29.      * 从属性配置中生成我们的布局参数 
  30.      */  
  31.     @Override  
  32.     public android.view.ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {  
  33.         return new CustomLayoutParams(getContext(), attrs);  
  34.     }  
  35.   
  36.     /** 
  37.      * 检查当前布局参数是否是我们定义的类型这在code声明布局参数时常常用到 
  38.      */  
  39.     @Override  
  40.     protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams p) {  
  41.         return p instanceof CustomLayoutParams;  
  42.     }  
  43.   
  44.     // 省略部分代码…………  
  45. }  
最后更改我们的测量逻辑:

[java]  view plain copy print ?
  1. @Override  
  2. protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  3.     // 声明临时变量存储父容器的期望值  
  4.     int parentDesireWidth = 0;  
  5.     int parentDesireHeight = 0;  
  6.   
  7.     /* 
  8.      * 如果有子元素 
  9.      */  
  10.     if (getChildCount() > 0) {  
  11.         // 那么遍历子元素并对其进行测量  
  12.         for (int i = 0; i < getChildCount(); i++) {  
  13.   
  14.             // 获取子元素  
  15.             View child = getChildAt(i);  
  16.   
  17.             // 获取子元素的布局参数  
  18.             CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();  
  19.   
  20.             // 测量子元素并考虑外边距  
  21.             measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);  
  22.   
  23.             // 计算父容器的期望值  
  24.             parentDesireWidth += child.getMeasuredWidth() + clp.leftMargin + clp.rightMargin;  
  25.             parentDesireHeight += child.getMeasuredHeight() + clp.topMargin + clp.bottomMargin;  
  26.         }  
  27.   
  28.         // 考虑父容器的内边距  
  29.         parentDesireWidth += getPaddingLeft() + getPaddingRight();  
  30.         parentDesireHeight += getPaddingTop() + getPaddingBottom();  
  31.   
  32.         // 尝试比较建议最小值和期望值的大小并取大值  
  33.         parentDesireWidth = Math.max(parentDesireWidth, getSuggestedMinimumWidth());  
  34.         parentDesireHeight = Math.max(parentDesireHeight, getSuggestedMinimumHeight());  
  35.     }  
  36.   
  37.     // 设置最终测量值O  
  38.     setMeasuredDimension(resolveSize(parentDesireWidth, widthMeasureSpec), resolveSize(parentDesireHeight, heightMeasureSpec));  
  39. }  
  40.   
  41. @Override  
  42. protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  43.     // 获取父容器内边距  
  44.     int parentPaddingLeft = getPaddingLeft();  
  45.     int parentPaddingTop = getPaddingTop();  
  46.   
  47.     /* 
  48.      * 如果有子元素 
  49.      */  
  50.     if (getChildCount() > 0) {  
  51.         // 声明一个临时变量存储高度倍增值  
  52.         int mutilHeight = 0;  
  53.   
  54.         // 那么遍历子元素并对其进行定位布局  
  55.         for (int i = 0; i < getChildCount(); i++) {  
  56.             // 获取一个子元素  
  57.             View child = getChildAt(i);  
  58.   
  59.             CustomLayoutParams clp = (CustomLayoutParams) child.getLayoutParams();  
  60.   
  61.             // 通知子元素进行布局  
  62.             // 此时考虑父容器内边距和子元素外边距的影响  
  63.             child.layout(parentPaddingLeft + clp.leftMargin, mutilHeight + parentPaddingTop + clp.topMargin, child.getMeasuredWidth() + parentPaddingLeft + clp.leftMargin, child.getMeasuredHeight() + mutilHeight + parentPaddingTop + clp.topMargin);  
  64.   
  65.             // 改变高度倍增值  
  66.             mutilHeight += child.getMeasuredHeight() + clp.topMargin + clp.bottomMargin;  
  67.         }  
  68.     }  
  69. }  
布局文件如下:

[html]  view plain copy print ?
  1. <com.aigestudio.customviewdemo.views.CustomLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:background="#FF597210"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <com.aigestudio.customviewdemo.views.IconView  
  8.         android:id="@+id/main_pv"  
  9.         android:layout_width="wrap_content"  
  10.         android:layout_height="wrap_content"  
  11.         android:layout_marginBottom="10dp"  
  12.         android:layout_marginLeft="20dp"  
  13.         android:layout_marginRight="30dp"  
  14.         android:layout_marginTop="5dp" />  
  15.   
  16.     <Button  
  17.         android:layout_width="wrap_content"  
  18.         android:layout_height="wrap_content"  
  19.         android:layout_marginBottom="16dp"  
  20.         android:layout_marginLeft="2dp"  
  21.         android:layout_marginRight="8dp"  
  22.         android:layout_marginTop="4dp"  
  23.         android:text="AigeStudio" />  
  24.   
  25.     <TextView  
  26.         android:layout_width="wrap_content"  
  27.         android:layout_height="wrap_content"  
  28.         android:layout_marginBottom="28dp"  
  29.         android:layout_marginLeft="7dp"  
  30.         android:layout_marginRight="19dp"  
  31.         android:layout_marginTop="14dp"  
  32.         android:background="#FF166792"  
  33.         android:text="AigeStudio" />  
  34.   
  35. </com.aigestudio.customviewdemo.views.CustomLayout>  
运行效果如下:


~~~~~~~~好了好了、不讲了,View的基本测量过程大致就是这样,如我所说测量并不是定式的过程,总会因控件而已,我们在自定义控件时要准确地测量,一定要准确,测量的结果会直接影响后面的布局定位、绘制甚至交互,所以马虎不得,你也可以看到Android给我们提供的LinearLayout、FrameLayout等布局都有极其严谨的测量逻辑,为的就是确保测量结果的准确。
本篇幅虽长,但是我们其实就讲了三点:

  1. 一个界面窗口的元素构成
  2. framework对View测量的控制处理
  3. View和ViewGroup的简单测量

好了、不说了、实在说不动了………………到此为止&¥……#¥……%#¥%#¥%#%¥哦!对了,文章开头我给各位设了一个问题,不知道大家发现没有,本来说这节顺带讲了,看着篇幅太长下节再说吧……

源码下载:传送门

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值