自定义ViewGroup-第二十一步:Measure与Layout

前言

根据启舰大大 的博客所学习的自定义View。

一、测量

1. MeasureSpec

MeasureSpec.getMode(int spec) //获取MODE  
MeasureSpec.getSize(int spec) //获取数值
  • MODE:
  • MeasureSpec.AT_MOST(至多):子元素至多达到指定大小的值->wrap_content。
  • MeasureSpec.EXACTLY(完全):父元素决定自元素的确切大小,子元素将被限定在给定的边界里而忽略它本身大小->match_parent。
  • MeasureSpec.UNSPECIFIED(未指定):父元素不对子元素施加任何束缚,子元素可以得到任意想要的大小->具体值。

2. onMeasure()

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  

一般用法举例:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
    int measureWidth = MeasureSpec.getSize(widthMeasureSpec);  
    int measureHeight = MeasureSpec.getSize(heightMeasureSpec);  
    int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);  
    int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);  
      
    //经过计算,控件所占的宽和高分别对应width和height  
    …………  
      
    setMeasuredDimension((measureWidthMode == MeasureSpec.EXACTLY) ? measureWidth: width, (measureHeightMode == MeasureSpec.EXACTLY) ? measureHeight: height);  
}  

3. measureChild与measureChildren
measureChild用来测量子View的宽高

//
protected void measureChild(View child, int parentWidthMeasureSpec,  
            int parentHeightMeasureSpec);

measureChildren是用来测量所有子View的宽高

protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {  
        final int size = mChildrenCount;  
        final View[] children = mChildren;  
        for (int i = 0; i < size; ++i) {  
            final View child = children[i];  
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {  
                measureChild(child, widthMeasureSpec, heightMeasureSpec);  
            }  
        }  
    } 

二、onLayout():实现所有子控件布局的函数

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

自定义实现简易的纵向LinearLayout:

public class MyLinear extends ViewGroup {
    public MyLinear(Context context) {
        this(context, null);
    }

    public MyLinear(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(measureWidth);
        int heightMode = MeasureSpec.getMode(measureHeight);
        int height=0;
        int width=0;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            measureChild(child,widthMeasureSpec,heightMeasureSpec);
            int childHeight=child.getMeasuredHeight();
            int childWidth=child.getMeasuredWidth();
            height+=childHeight;
            width=Math.max(width,childWidth);
        }
        setMeasuredDimension((widthMode==MeasureSpec.EXACTLY)?measureWidth:width,(heightMode==MeasureSpec.EXACTLY)?measureHeight:height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int top = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            child.layout(l, top, l + child.getMeasuredWidth(), top + child.getMeasuredHeight());
            top += child.getMeasuredHeight();
        }
    }
}
    <com.crossroads.demo.demo.MyLinear
        android:background="#00ff00"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TextView
            android:background="@color/colorPrimary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="自定义"
            />
        <TextView
            android:background="@color/colorPrimary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="实现"
            />
        <TextView
            android:background="@color/colorPrimary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="简易LinearLayout效果"
            />
    </com.crossroads.demo.demo.MyLinear>
效果图

getMeasuredWidth()与getWidth()区别

  • getMeasureWidth()方法在measure()过程结束后就可以获取到了,
    而getWidth()方法要在layout()过程结束后才能获取到
  • getMeasureWidth()方法中的值是通过setMeasuredDimension()方法来进行设置的,而getWidth()方法中的值则是通过layout(left,top,right,bottom)方法设置的。

三、获取子控件Margin

上边的例子中,发现设置margin无效,那么该怎么设置margin呢?
只需要重写下边这三个方法就可以获取到Margin啦

   @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new  MarginLayoutParams(getContext(),attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
    }

然后,onLayout和onMeasure也需要将margin计算进去滴

  @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(measureWidth);
        int heightMode = MeasureSpec.getMode(measureHeight);
        int height=0;
        int width=0;
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            measureChild(child,widthMeasureSpec,heightMeasureSpec);
            MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();

            int childHeight=child.getMeasuredHeight()+layoutParams.bottomMargin+layoutParams.topMargin;
            int childWidth=child.getMeasuredWidth()+layoutParams.leftMargin+layoutParams.rightMargin;
            height+=childHeight;
            width=Math.max(width,childWidth);
        }
        setMeasuredDimension((widthMode==MeasureSpec.EXACTLY)?measureWidth:width,(heightMode==MeasureSpec.EXACTLY)?measureHeight:height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int top = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
            child.layout(l+layoutParams.leftMargin, top+layoutParams.topMargin, l + child.getMeasuredWidth()+layoutParams.leftMargin, top + child.getMeasuredHeight()+layoutParams.topMargin);
            top += child.getMeasuredHeight()+layoutParams.topMargin+layoutParams.bottomMargin;
        }
    }
 <com.crossroads.demo.demo.MyLinear
        android:background="#00ff00"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_marginTop="5dp"
            android:background="@color/colorPrimary"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="自定义"
            />
        <TextView
            android:layout_margin="10dp"
            android:background="@color/colorPrimary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="实现"
            />
        <TextView
            android:layout_marginBottom="10dp"
            android:background="@color/colorPrimary"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="简易LinearLayout效果"
            />
    </com.crossroads.demo.demo.MyLinear>
flow

四、接下来完成这个效果

自适应

代码如下:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="180dp"/>
    <padding
        android:bottom="3dp"
        android:left="5dp"
        android:right="5dp"
        android:top="3dp"/>
    <solid android:color="#fff"/>
</shape>
public class FlowLayout extends ViewGroup {
    public FlowLayout(Context context) {
        super(context);
    }

    public FlowLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(measureHeight);
        int height = 0;//viewGroup高度
        int lineWidth = 0;//累加当前行的行宽
        int lineHeight = 0;//当前行的行高
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            measureChild(child, widthMeasureSpec, heightMeasureSpec);
            MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
            int childWidthWithMargin = child.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
            int childHeightWithMargin = child.getMeasuredHeight() + layoutParams.topMargin + layoutParams.bottomMargin;
            if (lineWidth + childWidthWithMargin > measureWidth) {
                //换行
                lineWidth = childWidthWithMargin;
                height += lineHeight;
                lineHeight = childHeightWithMargin;
            }
            else {
                //不换行
                lineHeight = Math.max(childHeightWithMargin, lineHeight);
                lineWidth += childWidthWithMargin;
            }
            //最后一行还没有计算呢
            if (i == childCount - 1) {
                height += lineHeight;
            }
        }
        setMeasuredDimension(measureWidth, (heightMode == MeasureSpec.EXACTLY) ? measureHeight : height);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int childCount = getChildCount();
        int top = 0;
        int lineWidth = 0, lineHeight = 0;
        for (int i = 0; i < childCount; i++) {
            View child = getChildAt(i);
            MarginLayoutParams layoutParams = (MarginLayoutParams) child.getLayoutParams();
            int childWidthWithMargin = child.getMeasuredWidth() + layoutParams.leftMargin + layoutParams.rightMargin;
            int childHeightWithMargin = child.getMeasuredHeight() + layoutParams.topMargin + layoutParams.bottomMargin;
            if (lineWidth + childWidthWithMargin > getMeasuredWidth()) {
                //换行
                top += lineHeight;
                child.layout(layoutParams.leftMargin, top + layoutParams.topMargin, layoutParams.leftMargin + child.getMeasuredWidth(), top + layoutParams.topMargin + child.getMeasuredHeight());
                lineWidth = childWidthWithMargin;
                lineHeight = childHeightWithMargin;
            }
            else {
                //不换行
                child.layout(lineWidth + layoutParams.leftMargin, top + layoutParams.topMargin, lineWidth + layoutParams.leftMargin + child.getMeasuredWidth(), top + layoutParams.topMargin + child.getMeasuredHeight());
                lineHeight = Math.max(childHeightWithMargin, lineHeight);
                lineWidth += childWidthWithMargin;
            }
        }
    }

    @Override
    protected LayoutParams generateLayoutParams(LayoutParams p) {
        return new MarginLayoutParams(p);
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

    @Override
    protected LayoutParams generateDefaultLayoutParams() {
        return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    }
}
  <com.crossroads.demo.demo.FlowLayout
        android:id="@+id/flowLayout"
        android:background="#00ff00"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
  final FlowLayout flowLayout = (FlowLayout) findViewById(R.id.flowLayout);
        flowLayout.removeAllViews();
        for (int i = 0; i < 10; i++) {
            final TextView child = new TextView(this);
            if (i % 7 == 0 || i % 7 == 1)
                child.setText("两只老虎" + i);
            else if (i % 7 == 2 || i % 7 == 3)
                child.setText("跑得快" + i);
            else if (i % 7 == 4 )
                child.setText("一只没有尾巴,一只没有眼睛" + i);
            else
                child.setText("真奇怪" + i);
            child.setTextSize(20);
            child.setBackgroundResource(R.drawable.roundrect);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
            params.setMargins(3, 4, 5, 7);
            child.setLayoutParams(params);
            child.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    flowLayout.removeView(child);
                }
            });
            flowLayout.addView(child);
        }
    }

参考网址

自定义View中的onMeasure,measureChild与measureChildren

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,185评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,445评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,684评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,564评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,681评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,874评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,025评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,761评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,217评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,545评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,694评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,351评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,988评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,778评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,007评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,427评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,580评论 2 349

推荐阅读更多精彩内容