欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Android 手把手教您自定义ViewGroup(一)

程序员文章站 2022-05-05 12:11:15
...


转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38339817 , 本文出自:【张鸿洋的博客】

最近由于工作的变动,导致的博客的更新计划有点被打乱,希望可以尽快脉动回来~

今天给大家带来一篇自定义ViewGroup的教程,说白了,就是教大家如何自定义ViewGroup,如果你对自定义ViewGroup还不是很了解,或者正想学习如何自定义,那么你可以好好看看这篇博客。

1、概述

在写代码之前,我必须得问几个问题:

1、ViewGroup的职责是啥?

ViewGroup相当于一个放置View的容器,并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属性,都是为用于告诉容器的),我们的宽度(layout_width)、高度(layout_height)、对齐方式(layout_gravity)等;当然还有margin等;于是乎,ViewGroup的职能为:给childView计算出建议的宽和高和测量模式 ;决定childView的位置;为什么只是建议的宽和高,而不是直接确定呢,别忘了childView宽和高可以设置为wrap_content,这样只有childView才能计算出自己的宽和高。

2、View的职责是啥?

View的职责,根据测量模式和ViewGroup给出的建议的宽和高,计算出自己的宽和高;同时还有个更重要的职责是:在ViewGroup为其指定的区域内绘制自己的形态。

3、ViewGroup和LayoutParams之间的关系?

大家可以回忆一下,当在LinearLayout中写childView的时候,可以写layout_gravity,layout_weight属性;在RelativeLayout中的childView有layout_centerInParent属性,却没有layout_gravity,layout_weight,这是为什么呢?这是因为每个ViewGroup需要指定一个LayoutParams,用于确定支持childView支持哪些属性,比如LinearLayout指定LinearLayout.LayoutParams等。如果大家去看LinearLayout的源码,会发现其内部定义了LinearLayout.LayoutParams,在此类中,你可以发现weight和gravity的身影。

2、View的3种测量模式

上面提到了ViewGroup会为childView指定测量模式,下面简单介绍下三种测量模式:

EXACTLY:表示设置了精确的值,一般当childView设置其宽、高为精确值、match_parent时,ViewGroup会将其设置为EXACTLY;

AT_MOST:表示子布局被限制在一个最大值内,一般当childView设置其宽、高为wrap_content时,ViewGroup会将其设置为AT_MOST;

UNSPECIFIED:表示子布局想要多大就多大,一般出现在AadapterView的item的heightMode中、ScrollView的childView的heightMode中;此种模式比较少见。

注:上面的每一行都有一个一般,意思上述不是绝对的,对于childView的mode的设置还会和ViewGroup的测量mode有一定的关系;当然了,这是第一篇自定义ViewGroup,而且绝大部分情况都是上面的规则,所以为了通俗易懂,暂不深入讨论其他内容。

3、从API角度进行浅析

上面叙述了ViewGroup和View的职责,下面从API角度进行浅析。

View的根据ViewGroup传人的测量值和模式,对自己宽高进行确定(onMeasure中完成),然后在onDraw中完成对自己的绘制。

ViewGroup需要给View传入view的测量值和模式(onMeasure中完成),而且对于此ViewGroup的父布局,自己也需要在onMeasure中完成对自己宽和高的确定。此外,需要在onLayout中完成对其childView的位置的指定。

4、完整的例子

需求:我们定义一个ViewGroup,内部可以传入0到4个childView,分别依次显示在左上角,右上角,左下角,右下角。

1、决定该ViewGroup的LayoutParams

对于我们这个例子,我们只需要ViewGroup能够支持margin即可,那么我们直接使用系统的MarginLayoutParams

  1. @Override  
  2.     public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)  
  3.     {  
  4.         return new MarginLayoutParams(getContext(), attrs);  
  5.     }  
@Override 
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
{
return new MarginLayoutParams(getContext(), attrs);
}

重写父类的该方法,返回MarginLayoutParams的实例,这样就为我们的ViewGroup指定了其LayoutParams为MarginLayoutParams。

2、onMeasure

在onMeasure中计算childView的测量值以及模式,以及设置自己的宽和高:

  1. / 
  2.       计算所有ChildView的宽度和高度 然后根据ChildView的计算结果,设置自己的宽和高 
  3.      /  
  4.     @Override  
  5.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  6.     {  
  7.         / 
  8.           获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式 
  9.          /  
  10.         int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  11.         int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  12.         int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);  
  13.         int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);  
  14.   
  15.   
  16.         // 计算出所有的childView的宽和高  
  17.         measureChildren(widthMeasureSpec, heightMeasureSpec);  
  18.         / 
  19.           记录如果是wrap_content是设置的宽和高 
  20.          /  
  21.         int width = 0;  
  22.         int height = 0;  
  23.   
  24.         int cCount = getChildCount();  
  25.   
  26.         int cWidth = 0;  
  27.         int cHeight = 0;  
  28.         MarginLayoutParams cParams = null;  
  29.   
  30.         // 用于计算左边两个childView的高度  
  31.         int lHeight = 0;  
  32.         // 用于计算右边两个childView的高度,最终高度取二者之间大值  
  33.         int rHeight = 0;  
  34.   
  35.         // 用于计算上边两个childView的宽度  
  36.         int tWidth = 0;  
  37.         // 用于计算下面两个childiew的宽度,最终宽度取二者之间大值  
  38.         int bWidth = 0;  
  39.   
  40.         / 
  41.           根据childView计算的出的宽和高,以及设置的margin计算容器的宽和高,主要用于容器是warp_content时 
  42.          /  
  43.         for (int i = 0; i < cCount; i++)  
  44.         {  
  45.             View childView = getChildAt(i);  
  46.             cWidth = childView.getMeasuredWidth();  
  47.             cHeight = childView.getMeasuredHeight();  
  48.             cParams = (MarginLayoutParams) childView.getLayoutParams();  
  49.   
  50.             // 上面两个childView  
  51.             if (i == 0 || i == 1)  
  52.             {  
  53.                 tWidth += cWidth + cParams.leftMargin + cParams.rightMargin;  
  54.             }  
  55.   
  56.             if (i == 2 || i == 3)  
  57.             {  
  58.                 bWidth += cWidth + cParams.leftMargin + cParams.rightMargin;  
  59.             }  
  60.   
  61.             if (i == 0 || i == 2)  
  62.             {  
  63.                 lHeight += cHeight + cParams.topMargin + cParams.bottomMargin;  
  64.             }  
  65.   
  66.             if (i == 1 || i == 3)  
  67.             {  
  68.                 rHeight += cHeight + cParams.topMargin + cParams.bottomMargin;  
  69.             }  
  70.   
  71.         }  
  72.           
  73.         width = Math.max(tWidth, bWidth);  
  74.         height = Math.max(lHeight, rHeight);  
  75.   
  76.         / 
  77.           如果是wrap_content设置为我们计算的值 
  78.           否则:直接设置为父容器计算的值 
  79.          */  
  80.         setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth  
  81.                 : width, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight  
  82.                 : height);  
  83.     }  
/ 
* 计算所有ChildView的宽度和高度 然后根据ChildView的计算结果,设置自己的宽和高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
/**
* 获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式
*/
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);

    // 计算出所有的childView的宽和高
    measureChildren(widthMeasureSpec, heightMeasureSpec);
    /**
     * 记录如果是wrap_content是设置的宽和高
     */
    int width = 0;
    int height = 0;

    int cCount = getChildCount();

    int cWidth = 0;
    int cHeight = 0;
    MarginLayoutParams cParams = null;

    // 用于计算左边两个childView的高度
    int lHeight = 0;
    // 用于计算右边两个childView的高度,最终高度取二者之间大值
    int rHeight = 0;

    // 用于计算上边两个childView的宽度
    int tWidth = 0;
    // 用于计算下面两个childiew的宽度,最终宽度取二者之间大值
    int bWidth = 0;

    /**
     * 根据childView计算的出的宽和高,以及设置的margin计算容器的宽和高,主要用于容器是warp_content时
     */
    for (int i = 0; i &lt; cCount; i++)
    {
        View childView = getChildAt(i);
        cWidth = childView.getMeasuredWidth();
        cHeight = childView.getMeasuredHeight();
        cParams = (MarginLayoutParams) childView.getLayoutParams();

        // 上面两个childView
        if (i == 0 || i == 1)
        {
            tWidth += cWidth + cParams.leftMargin + cParams.rightMargin;
        }

        if (i == 2 || i == 3)
        {
            bWidth += cWidth + cParams.leftMargin + cParams.rightMargin;
        }

        if (i == 0 || i == 2)
        {
            lHeight += cHeight + cParams.topMargin + cParams.bottomMargin;
        }

        if (i == 1 || i == 3)
        {
            rHeight += cHeight + cParams.topMargin + cParams.bottomMargin;
        }

    }

    width = Math.max(tWidth, bWidth);
    height = Math.max(lHeight, rHeight);

    /**
     * 如果是wrap_content设置为我们计算的值
     * 否则:直接设置为父容器计算的值
     */
    setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth
            : width, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight
            : height);
}</pre><br>10-14行,获取该ViewGroup父容器为其设置的计算模式和尺寸,大多情况下,只要不是wrap_content,父容器都能正确的计算其尺寸。所以我们自己需要计算如果设置为wrap_content时的宽和高,如何计算呢?那就是通过其childView的宽和高来进行计算。<p></p><p>17行,通过ViewGroup的measureChildren方法为其所有的孩子设置宽和高,此行执行完成后,childView的宽和高都已经正确的计算过了</p><p>43-71行,根据childView的宽和高,以及margin,计算ViewGroup在wrap_content时的宽和高。</p><p>80-82行,如果宽高属性值为wrap_content,则设置为43-71行中计算的值,否则为其父容器传入的宽和高。</p><h3><a name="t9" target="_blank"></a>3、onLayout对其所有childView进行定位(设置childView的绘制区域)</h3><p></p><div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><b>[java]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" target="_blank">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" target="_blank">copy</a><div style="position: absolute; left: 461px; top: 4237px; width: 18px; height: 18px; z-index: 99;"><embed id="ZeroClipboardMovie_3" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="18" height="18" name="ZeroClipboardMovie_3" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=3&amp;width=18&amp;height=18" wmode="transparent"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" target="_blank">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;" target="_blank">?</a></div></div><ol start="1" class="dp-j"><li class="alt"><span><span class="comment">//&nbsp;abstract&nbsp;method&nbsp;in&nbsp;viewgroup</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="annotation">@Override</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">protected</span><span>&nbsp;</span><span class="keyword">void</span><span>&nbsp;onLayout(</span><span class="keyword">boolean</span><span>&nbsp;changed,&nbsp;</span><span class="keyword">int</span><span>&nbsp;l,&nbsp;</span><span class="keyword">int</span><span>&nbsp;t,&nbsp;</span><span class="keyword">int</span><span>&nbsp;r,&nbsp;</span><span class="keyword">int</span><span>&nbsp;b)&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">int</span><span>&nbsp;cCount&nbsp;=&nbsp;getChildCount();&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">int</span><span>&nbsp;cWidth&nbsp;=&nbsp;</span><span class="number">0</span><span>;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">int</span><span>&nbsp;cHeight&nbsp;=&nbsp;</span><span class="number">0</span><span>;&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MarginLayoutParams&nbsp;cParams&nbsp;=&nbsp;<span class="keyword">null</span><span>;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="comment">/**</span>&nbsp;</span></li><li class=""><span><span class="comment">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*&nbsp;遍历所有childView根据其宽和高,以及margin进行布局</span>&nbsp;</span></li><li class="alt"><span><span class="comment">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;*/</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">for</span><span>&nbsp;(</span><span class="keyword">int</span><span>&nbsp;i&nbsp;=&nbsp;</span><span class="number">0</span><span>;&nbsp;i&nbsp;&lt;&nbsp;cCount;&nbsp;i++)&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;View&nbsp;childView&nbsp;=&nbsp;getChildAt(i);&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cWidth&nbsp;=&nbsp;childView.getMeasuredWidth();&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cHeight&nbsp;=&nbsp;childView.getMeasuredHeight();&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cParams&nbsp;=&nbsp;(MarginLayoutParams)&nbsp;childView.getLayoutParams();&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">int</span><span>&nbsp;cl&nbsp;=&nbsp;</span><span class="number">0</span><span>,&nbsp;ct&nbsp;=&nbsp;</span><span class="number">0</span><span>,&nbsp;cr&nbsp;=&nbsp;</span><span class="number">0</span><span>,&nbsp;cb&nbsp;=&nbsp;</span><span class="number">0</span><span>;&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">switch</span><span>&nbsp;(i)&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">case</span><span>&nbsp;</span><span class="number">0</span><span>:&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cl&nbsp;=&nbsp;cParams.leftMargin;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ct&nbsp;=&nbsp;cParams.topMargin;&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">break</span><span>;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">case</span><span>&nbsp;</span><span class="number">1</span><span>:&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cl&nbsp;=&nbsp;getWidth()&nbsp;-&nbsp;cWidth&nbsp;-&nbsp;cParams.leftMargin&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;cParams.rightMargin;&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ct&nbsp;=&nbsp;cParams.topMargin;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">break</span><span>;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">case</span><span>&nbsp;</span><span class="number">2</span><span>:&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cl&nbsp;=&nbsp;cParams.leftMargin;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ct&nbsp;=&nbsp;getHeight()&nbsp;-&nbsp;cHeight&nbsp;-&nbsp;cParams.bottomMargin;&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">break</span><span>;&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">case</span><span>&nbsp;</span><span class="number">3</span><span>:&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cl&nbsp;=&nbsp;getWidth()&nbsp;-&nbsp;cWidth&nbsp;-&nbsp;cParams.leftMargin&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-&nbsp;cParams.rightMargin;&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ct&nbsp;=&nbsp;getHeight()&nbsp;-&nbsp;cHeight&nbsp;-&nbsp;cParams.bottomMargin;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="keyword">break</span><span>;&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cr&nbsp;=&nbsp;cl&nbsp;+&nbsp;cWidth;&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;cb&nbsp;=&nbsp;cHeight&nbsp;+&nbsp;ct;&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;childView.layout(cl,&nbsp;ct,&nbsp;cr,&nbsp;cb);&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;&nbsp;</span></li></ol></div><pre name="code" class="java" style="display: none;">// abstract method in viewgroup
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
    int cCount = getChildCount();
    int cWidth = 0;
    int cHeight = 0;
    MarginLayoutParams cParams = null;
    /**
     * 遍历所有childView根据其宽和高,以及margin进行布局
     */
    for (int i = 0; i &lt; cCount; i++)
    {
        View childView = getChildAt(i);
        cWidth = childView.getMeasuredWidth();
        cHeight = childView.getMeasuredHeight();
        cParams = (MarginLayoutParams) childView.getLayoutParams();

        int cl = 0, ct = 0, cr = 0, cb = 0;

        switch (i)
        {
        case 0:
            cl = cParams.leftMargin;
            ct = cParams.topMargin;
            break;
        case 1:
            cl = getWidth() - cWidth - cParams.leftMargin
                    - cParams.rightMargin;
            ct = cParams.topMargin;

            break;
        case 2:
            cl = cParams.leftMargin;
            ct = getHeight() - cHeight - cParams.bottomMargin;
            break;
        case 3:
            cl = getWidth() - cWidth - cParams.leftMargin
                    - cParams.rightMargin;
            ct = getHeight() - cHeight - cParams.bottomMargin;
            break;

        }
        cr = cl + cWidth;
        cb = cHeight + ct;
        childView.layout(cl, ct, cr, cb);
    }

}</pre><br>代码比较容易懂:遍历所有的childView,根据childView的宽和高以及margin,然后分别将0,1,2,3位置的childView依次设置到左上、右上、左下、右下的位置。<p></p><p>如果是第一个View(index=0) :则childView.layout(cl, ct, cr, cb); cl为childView的leftMargin , ct 为topMargin , cr 为cl+ cWidth , cb为 ct + cHeight</p><p>如果是第二个View(index=1) :则childView.layout(cl, ct, cr, cb);&nbsp;</p><p>cl为getWidth() - cWidth - cParams.leftMargin- cParams.rightMargin;</p><p>ct 为topMargin , cr 为cl+ cWidth , cb为 ct + cHeight</p><p>剩下两个类似~</p><p>这样就完成了,我们的ViewGroup代码的编写,下面我们进行测试,分别设置宽高为固定值,wrap_content,match_parent</p><h2><a name="t10" target="_blank"></a>5、测试结果</h2><h3><a name="t11" target="_blank"></a>布局1:</h3><p></p><div class="dp-highlighter bg_html"><div class="bar"><div class="tools"><b>[html]</b> <a href="#" class="ViewSource" title="view plain" onclick="dp.sh.Toolbar.Command('ViewSource',this);return false;" target="_blank">view plain</a><span data-mod="popu_168"> <a href="#" class="CopyToClipboard" title="copy" onclick="dp.sh.Toolbar.Command('CopyToClipboard',this);return false;" target="_blank">copy</a><div style="position: absolute; left: 463px; top: 5608px; width: 18px; height: 18px; z-index: 99;"><embed id="ZeroClipboardMovie_4" src="http://static.blog.csdn.net/scripts/ZeroClipboard/ZeroClipboard.swf" loop="false" menu="false" quality="best" bgcolor="#ffffff" width="18" height="18" name="ZeroClipboardMovie_4" align="middle" allowscriptaccess="always" allowfullscreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" flashvars="id=4&amp;width=18&amp;height=18" wmode="transparent"></div></span><span data-mod="popu_169"> <a href="#" class="PrintSource" title="print" onclick="dp.sh.Toolbar.Command('PrintSource',this);return false;" target="_blank">print</a></span><a href="#" class="About" title="?" onclick="dp.sh.Toolbar.Command('About',this);return false;" target="_blank">?</a></div></div><ol start="1" class="dp-xml"><li class="alt"><span><span class="tag">&lt;</span><span class="tag-name">com.example.zhy_custom_viewgroup.CustomImgContainer</span><span>&nbsp;</span><span class="attribute">xmlns:android</span><span>=</span><span class="attribute-value">"http://schemas.android.com/apk/res/android"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">xmlns:tools</span><span>=</span><span class="attribute-value">"http://schemas.android.com/tools"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"200dp"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"200dp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#AA333333"</span><span>&nbsp;</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">TextView</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#FF4444"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:gravity</span><span>=</span><span class="attribute-value">"center"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:text</span><span>=</span><span class="attribute-value">"0"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textColor</span><span>=</span><span class="attribute-value">"#FFFFFF"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textSize</span><span>=</span><span class="attribute-value">"22sp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textStyle</span><span>=</span><span class="attribute-value">"bold"</span><span>&nbsp;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">TextView</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#00ff00"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:gravity</span><span>=</span><span class="attribute-value">"center"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:text</span><span>=</span><span class="attribute-value">"1"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textColor</span><span>=</span><span class="attribute-value">"#FFFFFF"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textSize</span><span>=</span><span class="attribute-value">"22sp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textStyle</span><span>=</span><span class="attribute-value">"bold"</span><span>&nbsp;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">TextView</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#ff0000"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:gravity</span><span>=</span><span class="attribute-value">"center"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:text</span><span>=</span><span class="attribute-value">"2"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textColor</span><span>=</span><span class="attribute-value">"#FFFFFF"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textSize</span><span>=</span><span class="attribute-value">"22sp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textStyle</span><span>=</span><span class="attribute-value">"bold"</span><span>&nbsp;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;<span class="tag">&lt;</span><span class="tag-name">TextView</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_width</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:layout_height</span><span>=</span><span class="attribute-value">"50dp"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:background</span><span>=</span><span class="attribute-value">"#0000ff"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:gravity</span><span>=</span><span class="attribute-value">"center"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:text</span><span>=</span><span class="attribute-value">"3"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textColor</span><span>=</span><span class="attribute-value">"#FFFFFF"</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textSize</span><span>=</span><span class="attribute-value">"22sp"</span><span>&nbsp;&nbsp;</span></span></li><li class="alt"><span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<span class="attribute">android:textStyle</span><span>=</span><span class="attribute-value">"bold"</span><span>&nbsp;</span><span class="tag">/&gt;</span><span>&nbsp;&nbsp;</span></span></li><li class=""><span>&nbsp;&nbsp;</span></li><li class="alt"><span><span class="tag">&lt;/</span><span class="tag-name">com.example.zhy_custom_viewgroup.CustomImgContainer</span><span class="tag">&gt;</span><span>&nbsp;&nbsp;</span></span></li></ol></div><pre name="code" class="html" style="display: none;">&lt;com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#AA333333" &gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#FF4444"
    android:gravity="center"
    android:text="0"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#00ff00"
    android:gravity="center"
    android:text="1"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#ff0000"
    android:gravity="center"
    android:text="2"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#0000ff"
    android:gravity="center"
    android:text="3"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

</com.example.zhy_custom_viewgroup.CustomImgContainer>

ViewGroup宽和高设置为固定值

效果图:

Android 手把手教您自定义ViewGroup(一)


布局2:

  1. <com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android=http://schemas.android.com/apk/res/android  
  2.     xmlns:tools=http://schemas.android.com/tools  
  3.     android:layout_width=“wrap_content”  
  4.     android:layout_height=“wrap_content”  
  5.     android:background=“#AA333333” >  
  6.   
  7.     <TextView  
  8.         android:layout_width=“150dp”  
  9.         android:layout_height=“150dp”  
  10.         android:background=“#E5ED05”  
  11.         android:gravity=“center”  
  12.         android:text=“0”  
  13.         android:textColor=“#FFFFFF”  
  14.         android:textSize=“22sp”  
  15.         android:textStyle=“bold” />  
  16.   
  17.     <TextView  
  18.         android:layout_width=“50dp”  
  19.         android:layout_height=“50dp”  
  20.         android:background=“#00ff00”  
  21.         android:gravity=“center”  
  22.         android:text=“1”  
  23.         android:textColor=“#FFFFFF”  
  24.         android:textSize=“22sp”  
  25.         android:textStyle=“bold” />  
  26.   
  27.     <TextView  
  28.         android:layout_width=“50dp”  
  29.         android:layout_height=“50dp”  
  30.         android:background=“#ff0000”  
  31.         android:gravity=“center”  
  32.         android:text=“2”  
  33.         android:textColor=“#FFFFFF”  
  34.         android:textSize=“22sp”  
  35.         android:textStyle=“bold” />  
  36.   
  37.     <TextView  
  38.         android:layout_width=“50dp”  
  39.         android:layout_height=“50dp”  
  40.         android:background=“#0000ff”  
  41.         android:gravity=“center”  
  42.         android:text=“3”  
  43.         android:textColor=“#FFFFFF”  
  44.         android:textSize=“22sp”  
  45.         android:textStyle=“bold” />  
  46.   
  47. </com.example.zhy_custom_viewgroup.CustomImgContainer>  
<com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#AA333333" >
&lt;TextView
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:background="#E5ED05"
    android:gravity="center"
    android:text="0"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#00ff00"
    android:gravity="center"
    android:text="1"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#ff0000"
    android:gravity="center"
    android:text="2"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#0000ff"
    android:gravity="center"
    android:text="3"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

</com.example.zhy_custom_viewgroup.CustomImgContainer>

ViewGroup的宽和高设置为wrap_content
效果图:

Android 手把手教您自定义ViewGroup(一)


布局3:

  1. <com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android=http://schemas.android.com/apk/res/android  
  2.     xmlns:tools=http://schemas.android.com/tools  
  3.     android:layout_width=“match_parent”  
  4.     android:layout_height=“match_parent”  
  5.     android:background=“#AA333333” >  
  6.   
  7.     <TextView  
  8.         android:layout_width=“150dp”  
  9.         android:layout_height=“150dp”  
  10.         android:background=“#E5ED05”  
  11.         android:gravity=“center”  
  12.         android:text=“0”  
  13.         android:textColor=“#FFFFFF”  
  14.         android:textSize=“22sp”  
  15.         android:textStyle=“bold” />  
  16.   
  17.     <TextView  
  18.         android:layout_width=“50dp”  
  19.         android:layout_height=“50dp”  
  20.         android:background=“#00ff00”  
  21.         android:gravity=“center”  
  22.         android:text=“1”  
  23.         android:textColor=“#FFFFFF”  
  24.         android:textSize=“22sp”  
  25.         android:textStyle=“bold” />  
  26.   
  27.     <TextView  
  28.         android:layout_width=“50dp”  
  29.         android:layout_height=“50dp”  
  30.         android:background=“#ff0000”  
  31.         android:gravity=“center”  
  32.         android:text=“2”  
  33.         android:textColor=“#FFFFFF”  
  34.         android:textSize=“22sp”  
  35.         android:textStyle=“bold” />  
  36.   
  37.     <TextView  
  38.         android:layout_width=“150dp”  
  39.         android:layout_height=“150dp”  
  40.         android:background=“#0000ff”  
  41.         android:gravity=“center”  
  42.         android:text=“3”  
  43.         android:textColor=“#FFFFFF”  
  44.         android:textSize=“22sp”  
  45.         android:textStyle=“bold” />  
  46.   
  47. </com.example.zhy_custom_viewgroup.CustomImgContainer>  
<com.example.zhy_custom_viewgroup.CustomImgContainer xmlns:android="http://schemas.android.com/apk/res/android" 
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#AA333333" >
&lt;TextView
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:background="#E5ED05"
    android:gravity="center"
    android:text="0"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#00ff00"
    android:gravity="center"
    android:text="1"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:background="#ff0000"
    android:gravity="center"
    android:text="2"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

&lt;TextView
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:background="#0000ff"
    android:gravity="center"
    android:text="3"
    android:textColor="#FFFFFF"
    android:textSize="22sp"
    android:textStyle="bold" /&gt;

</com.example.zhy_custom_viewgroup.CustomImgContainer>


ViewGroup的宽和高设置为match_parent

Android 手把手教您自定义ViewGroup(一)


可以看到无论ViewGroup的宽和高的值如何定义,我们的需求都实现了预期的效果

好了,通过这篇教程,希望大家已经能够初步掌握自定义ViewGroup的步骤,大家可以尝试自定义ViewGroup去实现LinearLayout的效果

最后说明下,此为第一篇ViewGroup的教程,以后还会进一步的探讨如何更好的自定义ViewGroup~~~


如果你觉得这篇文章对你有用,那么赞一个或者留个言吧~




源码点击下载





转自:http://blog.csdn.net/lmj623565791/article/details/38339817

转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/38339817 , 本文出自:【张鸿洋的博客】

最近由于工作的变动,导致的博客的更新计划有点被打乱,希望可以尽快脉动回来~

今天给大家带来一篇自定义ViewGroup的教程,说白了,就是教大家如何自定义ViewGroup,如果你对自定义ViewGroup还不是很了解,或者正想学习如何自定义,那么你可以好好看看这篇博客。

1、概述

在写代码之前,我必须得问几个问题:

1、ViewGroup的职责是啥?

ViewGroup相当于一个放置View的容器,并且我们在写布局xml的时候,会告诉容器(凡是以layout为开头的属性,都是为用于告诉容器的),我们的宽度(layout_width)、高度(layout_height)、对齐方式(layout_gravity)等;当然还有margin等;于是乎,ViewGroup的职能为:给childView计算出建议的宽和高和测量模式 ;决定childView的位置;为什么只是建议的宽和高,而不是直接确定呢,别忘了childView宽和高可以设置为wrap_content,这样只有childView才能计算出自己的宽和高。

2、View的职责是啥?

View的职责,根据测量模式和ViewGroup给出的建议的宽和高,计算出自己的宽和高;同时还有个更重要的职责是:在ViewGroup为其指定的区域内绘制自己的形态。

3、ViewGroup和LayoutParams之间的关系?

大家可以回忆一下,当在LinearLayout中写childView的时候,可以写layout_gravity,layout_weight属性;在RelativeLayout中的childView有layout_centerInParent属性,却没有layout_gravity,layout_weight,这是为什么呢?这是因为每个ViewGroup需要指定一个LayoutParams,用于确定支持childView支持哪些属性,比如LinearLayout指定LinearLayout.LayoutParams等。如果大家去看LinearLayout的源码,会发现其内部定义了LinearLayout.LayoutParams,在此类中,你可以发现weight和gravity的身影。

2、View的3种测量模式

上面提到了ViewGroup会为childView指定测量模式,下面简单介绍下三种测量模式:

EXACTLY:表示设置了精确的值,一般当childView设置其宽、高为精确值、match_parent时,ViewGroup会将其设置为EXACTLY;

AT_MOST:表示子布局被限制在一个最大值内,一般当childView设置其宽、高为wrap_content时,ViewGroup会将其设置为AT_MOST;

UNSPECIFIED:表示子布局想要多大就多大,一般出现在AadapterView的item的heightMode中、ScrollView的childView的heightMode中;此种模式比较少见。

注:上面的每一行都有一个一般,意思上述不是绝对的,对于childView的mode的设置还会和ViewGroup的测量mode有一定的关系;当然了,这是第一篇自定义ViewGroup,而且绝大部分情况都是上面的规则,所以为了通俗易懂,暂不深入讨论其他内容。

3、从API角度进行浅析

上面叙述了ViewGroup和View的职责,下面从API角度进行浅析。

View的根据ViewGroup传人的测量值和模式,对自己宽高进行确定(onMeasure中完成),然后在onDraw中完成对自己的绘制。

ViewGroup需要给View传入view的测量值和模式(onMeasure中完成),而且对于此ViewGroup的父布局,自己也需要在onMeasure中完成对自己宽和高的确定。此外,需要在onLayout中完成对其childView的位置的指定。

4、完整的例子

需求:我们定义一个ViewGroup,内部可以传入0到4个childView,分别依次显示在左上角,右上角,左下角,右下角。

1、决定该ViewGroup的LayoutParams

对于我们这个例子,我们只需要ViewGroup能够支持margin即可,那么我们直接使用系统的MarginLayoutParams

  1. @Override  
  2.     public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)  
  3.     {  
  4.         return new MarginLayoutParams(getContext(), attrs);  
  5.     }  
@Override 
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs)
{
return new MarginLayoutParams(getContext(), attrs);
}

重写父类的该方法,返回MarginLayoutParams的实例,这样就为我们的ViewGroup指定了其LayoutParams为MarginLayoutParams。

2、onMeasure

在onMeasure中计算childView的测量值以及模式,以及设置自己的宽和高:

  1. / 
  2.       计算所有ChildView的宽度和高度 然后根据ChildView的计算结果,设置自己的宽和高 
  3.      /  
  4.     @Override  
  5.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  6.     {  
  7.         / 
  8.           获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式 
  9.          /  
  10.         int widthMode = MeasureSpec.getMode(widthMeasureSpec);  
  11.         int heightMode = MeasureSpec.getMode(heightMeasureSpec);  
  12.         int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);  
  13.         int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);  
  14.   
  15.   
  16.         // 计算出所有的childView的宽和高  
  17.         measureChildren(widthMeasureSpec, heightMeasureSpec);  
  18.         / 
  19.           记录如果是wrap_content是设置的宽和高 
  20.          /  
  21.         int width = 0;  
  22.         int height = 0;  
  23.   
  24.         int cCount = getChildCount();  
  25.   
  26.         int cWidth = 0;  
  27.         int cHeight = 0;  
  28.         MarginLayoutParams cParams = null;  
  29.   
  30.         // 用于计算左边两个childView的高度  
  31.         int lHeight = 0;  
  32.         // 用于计算右边两个childView的高度,最终高度取二者之间大值  
  33.         int rHeight = 0;  
  34.   
  35.         // 用于计算上边两个childView的宽度  
  36.         int tWidth = 0;  
  37.         // 用于计算下面两个childiew的宽度,最终宽度取二者之间大值  
  38.         int bWidth = 0;  
  39.   
  40.         / 
  41.           根据childView计算的出的宽和高,以及设置的margin计算容器的宽和高,主要用于容器是warp_content时 
  42.          /  
  43.         for (int i = 0; i < cCount; i++)  
  44.         {  
  45.             View childView = getChildAt(i);  
  46.             cWidth = childView.getMeasuredWidth();  
  47.             cHeight = childView.getMeasuredHeight();  
  48.             cParams = (MarginLayoutParams) childView.getLayoutParams();  
  49.   
  50.             // 上面两个childView  
  51.             if (i == 0 || i == 1)  
  52.             {  
  53.                 tWidth += cWidth + cParams.leftMargin + cParams.rightMargin;  
  54.             }  
  55.   
  56.             if (i == 2 || i == 3)  
  57.             {  
  58.                 bWidth += cWidth + cParams.leftMargin + cParams.rightMargin;  
  59.             }  
  60.   
  61.             if (i == 0 || i == 2)  
  62.             {  
  63.                 lHeight += cHeight + cParams.topMargin + cParams.bottomMargin;  
  64.             }  
  65.   
  66.             if (i == 1 || i == 3)  
  67.             {  
  68.                 rHeight += cHeight + cParams.topMargin + cParams.bottomMargin;  
  69.             }  
  70.   
  71.         }  
  72.           
  73.         width = Math.max(tWidth, bWidth);  
  74.         height = Math.max(lHeight, rHeight);  
  75.   
  76.         / 
  77.           如果是wrap_content设置为我们计算的值 
  78.           否则:直接设置为父容器计算的值 
  79.          */  
  80.         setMeasuredDimension((widthMode == MeasureSpec.EXACTLY) ? sizeWidth  
  81.                 : width, (heightMode == MeasureSpec.EXACTLY) ? sizeHeight  
  82.                 : height);  
  83.     }  
/ 
* 计算所有ChildView的宽度和高度 然后根据ChildView的计算结果,设置自己的宽和高
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
/**
* 获得此ViewGroup上级容器为其推荐的宽和高,以及计算模式
*/
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int sizeWidth = MeasureSpec.getSize(widthMeasureSpec);
int sizeHeight = MeasureSpec.getSize(heightMeasureSpec);