Android自定义View介绍

  1. 为什么要学习自定义View
    在实际开发的过程中,我们会发现Android提供的原生控件无法满足我们开发的需要,于是乎,便需要进行自定义View了。说白了,自定义View是我们Android开发进阶的必经之路。

  2. 自定义View的基本方法
    自定义View最基本的三个方法分别是:onMeasure()、onLayout()、onDraw();View在Activity中显示出来,要经过测量、布局和绘制三个步骤,分别对应三个动作:measure、layout和draw。

测量:onMeasure()决定View的大小;
布局:onLayout()决定View在ViewGroup中的位置;
绘制:onDraw()决定绘制这个View。

  1. 自定义控件分类
    自定义View:只需要重写onMeasure()和onDraw()
    自定义ViewGroup:只需要重写onMeasure()和onLayout()
  2. 自定义View基础
    自定义View包含布局(onLayout、onMeasure)、显示(onDraw)、事件分发(onTouchEvent)。

4.1 View的分类
视图View主要分为两类

类别 描述
单一视图 即一个View,如TextView;不包含子View
视图组 即多个View组成的ViewGroup,如LinearLayout;包含子View

4.2 自定义View的绘制流程


image.png
image.png

4.2 View类简介
View类是Android中各种组件的基类,如View是ViewGroup基类
View表现为显示在屏幕上的各种视图
Android中的UI组件都由View、ViewGroup组成
View的构造函数:共有4个

    // 如果 View是在 Java代码里面 new的,则调用第一个构造函数
    public ViewTest(Context context) {
        super(context);
    }
    // 如果 View是在 .xml里声明的,则调用第二个构造函数
    // 自定义属性是从 AttributeSet参数传进来的
    public ViewTest(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    // 不会自动调用
    // 一般是在第二个构造函数里主动调用
    // 如 View有style属性时
    public ViewTest(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
    // API21之后才使用
    // 不会自动调用
    // 一般是在第二个构造函数里主动调用
    // 如 View有style属性时
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public ViewTest(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

4.3 AttributeSet与自定义属性
系统自带的View可以在xml中配置属性,对于写的好的自定义View同样可以在xml中配置属性,为了使自定义的View的属性可以在xml中配置,需要以下四个步骤:

通过< declare-styleable >为自定义View添加属性
在xml中为相应的属性声明属性值
在运行时(一般为构造函数)获取属性值
将获取到的属性值应用到View
4.4 View视图结构
PhoneWindow是Android系统中最基本的窗口系统,继承自Windows类,负责管理界面显示以及事件响应。它是Activity与View系统交互的接口。
DecorView是PhoneWindow中的起始节点View,继承于View类,作为整个视图容器来使用。用于设置窗口属性。它本质上是一个FrameLayout。
ViewRoot在Activity启动时创建,负责管理、布局、渲染窗口UI等等。


image.png

对于多View的视图,结构是树形结构:最顶层是ViewGroup,ViewGroup下可能有多个ViewGroup或View,如下图:


image.png

一定要记住:无论是measure过程、layout过程还是draw过程,永远都是从View树的根节点开始测量或计算(即从树的顶端开始),一层一层、一个分支一个分支地进行(即树形递归),最终计算整个View树中各个View,最终确定整个View树的相关属性。

4.5 Android坐标系
Android的坐标系定义为:

屏幕的左上角为坐标原点
向右为x轴增大方向,向下为y轴增大方向


image.png

image.png

4.6 View位置(坐标)描述
View的位置由4个顶点决定的4个顶点的位置描述分别由4个值决定:
View的位置时相对于父控件而言的

Top:子View上边界到父View上边界的距离
Left:子View左边界到父View左边界的距离
Bottom:子View下边界到父View上边界的距离
Right:子View右边界到父View左边界的距离
4.7 位置获取方式
View的位置时通过view.getxxx()函数进行获取:(以Top为例)

// 获取Top位置
public final int getTop() {
        return mTop;
    }

    // 其余如下:
    getLeft();  // 获取子View左上角距父View左侧的距离
    getBottom();    // 获取子View右下角距父View顶部的距离
    getRight(); // 获取子View右下角距父View左侧的距离

与MotionEvent中get()和getRaw()的区别:

// get():触摸点相对于其所在组件坐标系的坐标
event.getX();
event.getY();

// getRaw():触摸点相对于屏幕默认坐标系的坐标
event.getRawX();
event.getRawY();
  1. View树的绘制流程
    5.1 View树的绘制流程是谁负责的?
    view树的绘制流程是通过ViewRoot去负责绘制的,ViewRoot这个类的命名有点坑,最初看到这个名字,翻译过来是view的根节点,但是事实完全不是这样,ViewRoot其实不是View的根节点,它连view节点都算不上,它的主要作用是View树的管理者,负责将DecorView和PhoneWindow“组合”起来,而View树的根节点严格意义上来说只有DecorView;每个DecorView都有一个ViewRoot与之关联,这种关联关系是由WindowManager去进行管理的。

5.2 view的添加


image.png

5.3 view的绘制流程


image.png
  1. LayoutParams
    LayoutParams翻译过来就是布局参数,子View通过LayoutParams告诉父容器(ViewGroup)应该如何放置自己。从这个定义中可以看出来LayoutParams与ViewGroup是息息相关的,因此脱离ViewGroup谈LayoutParams是没有意义的。
    事实上,每个ViewGroup的子类都有自己对应的LayoutParams类,典型的如LinearLayout.LayoutParams和FrameLayout.LayoutParams等,可以看出来LayoutParams都有对应ViewGroup子类的内部类。

6.1 LayoutParams与View如何建立联系
在xml中定义View
在Java代码中直接生成View对应的实例对象
6.2 addView

/**
 * 重载方法1:添加一个子view
 * 如果这个子view还没有LayoutParams,就为子view设置当前ViewGroup默认的LayoutParams
 */
public void addView(View child) {
        addView(child, -1);
    }
/**
* 重载方法2:在指定位置添加一个子View
* 如果这个子View还没有LayoutParams,就为子View设置当前ViewGroup默认的LayoutParams
* @param index View将在ViewGroup中被添加的位置(-1代表添加到末尾)
*/
public void addView(View child, int index) {
    if (child == null) {
        throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
    }
    LayoutParams params = child.getLayoutParams();
    if (params == null) {
        params = generateDefaultLayoutParams();// 生成当前ViewGroup默认的LayoutParams
        if (params == null) {
            throw new IllegalArgumentException("generateDefaultLayoutParams() cannot return null");
        }
    }
    addView(child,index,params);
}

/**
 1. 重载方法3:添加一个子View
 2. 使用当前ViewGroup默认的LayoutParams,并以传入参数作为LayoutParams的width和height
*/
public void addView(View child, int width, int height) {
    final LayoutParams params = generateDefaultLayoutParams(); // 生成当前ViewGroup默认的LayoutParams
    params.width = width;
    params.height = height;
    addView(child, -1, params);
}
/**
 3. 重载方法4:添加一个子View,并使用传入的LayoutParams
*/
@Override
public void addView(View child, LayoutParams params) {
    addView(child, -1, params);
}
/**
 4. 重载方法4:在指定位置添加一个子View,并使用传入的LayoutParams
*/
public void addView(View child, int index, LayoutParams params) {
    if (child == null) {
        throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
}
    // addViewInner() will call child.requestLayout() when setting the new LayoutParams
    // therefore, we call requestLayout() on ourselves before, so that the child's request
    // will be blocked at our level
    requestLayout();
    invalidate(true);
    addViewInner(child, index, params, false);
}
private void addViewInner(View child, int index, LayoutParams params,boolean preventRequestLayout) {
    .....
    if (mTransition != null) {
        mTransition.addChild(this, child);
    }
    if (!checkLayoutParams(params)) { // ① 检查传入的LayoutParams是否合法
        params = generateLayoutParams(params); // 如果传入的LayoutParams不合法,将进行转化操作
    }
    if (preventRequestLayout) { // ② 是否需要阻止重新执行布局流程
        child.mLayoutParams = params; // 这不会引起子View重新布局(onMeasure->onLayout->onDraw)
    } else {
        child.setLayoutParams(params); // 这会引起子View重新布局(onMeasure->onLayout->onDraw)
    }
    if (index < 0) {
    index = mChildrenCount;
    }
    addInArray(child, index);
    // tell our children
    if (preventRequestLayout) {
        child.assignParent(this);
    } else {
        child.mParent = this;
    }
    .....
}

6.3 自定义LayoutParams
1.创建自定义属性

<resources>
    <declare-styleable name="xxxViewGroup_Layout">
        <!-- 自定义的属性 -->
        <attr name="layout_simple_attr" format="integer"/>
        <!-- 使用系统预置的属性 -->
        <attr name="android:layout_gravity"/>
    </declare-styleable>
</resources>

2.继承MarginLayout

public static class LayoutParams extends ViewGroup.MarginLayoutParams{
    public int simpleAttr;
    public int gravity;
    public LayoutParams(Context c, AttributeSet attrs) {
        super(c, attrs);
        // 解析布局属性
        TypedArray typedArray = c.obtainStyledAttributes(attrs,R.styleable.SimpleViewGroup_Layout);
        simpleAttr = typedArray.getInteger(R.styleable.SimpleViewGroup_Layout_layout_simple_attr, 0);
        gravity = typedArray.getInteger(R.styleable.SimpleViewGroup_Layout_android_layout_gravity,
-1);
        typedArray.recycle();//释放资源
    }
    public LayoutParams(int width, int height) {
        super(width, height);
    }
    public LayoutParams(MarginLayoutParams source) {
        super(source);
    }
    public LayoutParams(ViewGroup.LayoutParams source) {
        super(source);
    }
}

3.重写ViewGroup中几个与LayoutParams相关的方法

// 检查LayoutParams是否合法
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
    return p instanceof SimpleViewGroup.LayoutParams;
}
// 生成默认的LayoutParam
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
    return new SimpleViewGroup.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
}
// 对传入的LayoutParams进行转化
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
    return new SimpleViewGroup.LayoutParams(p);
}
// 对传入的LayoutParams进行转化
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
    return new SimpleViewGroup.LayoutParams(getContext(),attrs);
}

6.4 LayoutParams常见的子类
ViewGroup.MarginLayoutParams
FrameLayout.LayoutParams
LinearLayout.LayoutParams
RelativeLayout.LayoutParams
RecyclerView.LayoutParams
GridLayoutManager.LayoutParams
StaggeredGridLayoutManager.LayoutParams
ViewPager.LayoutParams
WindowManager.LayoutParams

  1. MeasureSpec
    7.1 定义
    MeasureSpec是View中的内部类,基本都是二进制运算。由于int是32位,用高2位表示mode(UNSPECIFIED、EXACTLY、AT_MOST),低30位表示size,MODE_SHIFT=30的作用是移位。
    测量规格,封装了父容器对view的布局上的限制,内部提供了宽高的信息(SpecMode、SpecSize),SpecSize是指在某种SpecMode下的参考尺寸,其中SpecMode有如下三种:

UNSPECIFIED:父控件不对你有任何限制,你想要多大给你多大,想上天就上天。这种情况一般用于系统内部,表示一种测量状态。(这个模式主要用于系统内部多次Measure的情形,并不是真的说你想要多大最后就真有多大)
EXACTLY:父控件已经知道你所需的精确大小,你的最终大小应该就是这么大。
AT_MOST:你的大小不能大于父控件给你指定的size,但具体是多少,得看你自己的实现。

specMode 描述
UNSPECIFIED 不对View大小做限制,系统使用
EXACTLY 确切的大小,如:100dp
AT_MOST 大小不可超过某数值,如:matchParent,最大不能超过父View
image.png

7.2 MeasureSpecs的意义

通过将SpecMode和SpecSize打包成一个int值可以避免过多的对象内存分配,为了方便操作,其提供了打包/解包方法

7.3 MeasureSpec值的确定

/**
*
* 目标是将父控件的测量规格和child view的布局参数LayoutParams相结合,得到一个
* 最可能符合条件的child view的测量规格。
* @param spec 父控件的测量规格
* @param padding 父控件里已经占用的大小
* @param childDimension child view布局LayoutParams里的尺寸
* @return child view 的测量规格
*/
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
    int specMode = MeasureSpec.getMode(spec); //父控件的测量模式
    int specSize = MeasureSpec.getSize(spec); //父控件的测量大小
    int size = Math.max(0, specSize - padding);
    int resultSize = 0;
    int resultMode = 0;
    switch (specMode) {
        // 当父控件的测量模式 是 精确模式,也就是有精确的尺寸了
        case MeasureSpec.EXACTLY:
            //如果child的布局参数有固定值,比如"layout_width" = "100dp"
            //那么显然child的测量规格也可以确定下来了,测量大小就是100dp,测量模式也是EXACTLY
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            }
            //如果child的布局参数是"match_parent",也就是想要占满父控件

            //而此时父控件是精确模式,也就是能确定自己的尺寸了,那child也能确定自己大小了
            else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            }
            //如果child的布局参数是"wrap_content",也就是想要根据自己的逻辑决定自己大小,
            //比如TextView根据设置的字符串大小来决定自己的大小
            //那就自己决定呗,不过你的大小肯定不能大于父控件的大小嘛
            //所以测量模式就是AT_MOST,测量大小就是父控件的size
            else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;
        // 当父控件的测量模式 是 最大模式,也就是说父控件自己还不知道自己的尺寸,但是大小不超过size
        case MeasureSpec.AT_MOST:
        //同样的,既然child能确定自己大小,尽管父控件自己还不知道自己大小,也优先满足孩子的需求??
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            }
            //child想要和父控件一样大,但父控件自己也不确定自己大小,所以child也无法确定自己大小
            //但同样的,child的尺寸上限也是父控件的尺寸上限size
            else if (childDimension == LayoutParams.MATCH_PARENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            //child想要根据自己逻辑决定大小,那就自己决定呗
            else if (childDimension == LayoutParams.WRAP_CONTENT) {
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;
        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let him have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = 0;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
    return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
}

7.4 普通View的MeasureSpec的创建规则

image.png

7.5 getMeasureWidth和getWidth的区别

getMeasureWidth:

在measure()过程结束后就可以获取到对应的值
通过setMeasuredDimension()方法来进行设置的
getWidth:

在layout()过程结束后才能获取到
通过视图右边的坐标减去左边的坐标计算出来的

8 自定义View的例子流式布局CustomFlowLayout:

package com.example.nqct.customview;

import android.content.Context;
import android.content.res.Resources;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义ViewGroup,流式布局
 */
public class CustomFlowLayout extends ViewGroup {

    private static final String TAG = CustomFlowLayout.class.getName();
    private int mHorizontalSpacing = dp2px(16); //每个item横向间距
    private int mVerticalSpacing = dp2px(8); //每个item横向间距

    //记录所有的行,一行一行的存储,用于layout,其中List<View>代表一行的所有View集合
    private List<List<View>> mAllLineViews = new ArrayList<>();
    //记录每一行的行高,用于layout
    private List<Integer> mLineHeights = new ArrayList<>();

    public CustomFlowLayout(Context context) {
        super(context);
    }

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

    public CustomFlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private void clearMeasureParams() {
        mAllLineViews.clear();
        mLineHeights.clear();
    }

    /**
     * 遍历子View,测量子View大小和测量父View本身大小
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //内存抖动
        clearMeasureParams();

        int childCount = getChildCount();

        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        Log.i(TAG, "onMeasure==>paddingLeft="+paddingLeft+", paddingRight="+paddingRight
            +", paddingTop="+paddingTop+", paddingBottom="+paddingBottom
            +", childCount="+childCount);

        //onMeasure==>viewGroupWidth=1080, viewGroupHeight=1990
        //当前ViewGroup的宽高(即CustomFlowLayout的宽高)
        int viewGroupWidth = MeasureSpec.getSize(widthMeasureSpec);
        int viewGroupHeight = MeasureSpec.getSize(heightMeasureSpec);
        //当前ViewGroup的测量模式(即CustomFlowLayout的测量模式)
        int viewGroupWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        int viewGroupHeightMode = MeasureSpec.getMode(heightMeasureSpec);

        List<View> lineViews = new ArrayList<>(); //保存一行中的所有的view
        int lineWidthUsed = 0; //记录这行已经使用了多宽的size
        int lineHeight = 0; // 一行的行高

        int parentNeededWidth = 0;  // measure过程中,子View要求的父ViewGroup的宽
        int parentNeededHeight = 0; // measure过程中,子View要求的父ViewGroup的高

        Log.i(TAG, "onMeasure==>viewGroupWidth="+viewGroupWidth+", viewGroupHeight="+viewGroupHeight);

        for (int i=0;i<childCount;i++) {
            View childView = getChildAt(i);
            ViewGroup.LayoutParams childLp = childView.getLayoutParams();
            //子view不为gone,才可以测量子view的宽高
            if (childView.getVisibility() != View.GONE) {
                /**
                 * 根据父view的测量规格结合子View的LayoutParams,得到符合条件的子View的测量规格
                 * getChildMeasureSpec:参数一:父View的spec,参数二:父View的padding,参数三:子View的宽或高
                 */
                int childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                        paddingLeft + paddingRight, childLp.width);
                int childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                        paddingTop + paddingBottom, childLp.height);
                //根据子view的测量规格,测量子View的宽高
                childView.measure(childWidthMeasureSpec, childHeightMeasureSpec);

                //获取子view的测量宽高
                int childMeasuredWidth = childView.getMeasuredWidth();
                int childMeasuredHeight = childView.getMeasuredHeight();

                //childView==>i=0, childWidthMeasureSpec=-2147482568, childHeightMeasureSpec=-2147481658, childMeasuredWidth=126, childMeasuredHeight=57
                Log.i(TAG, "childView==>i="+i+", childWidthMeasureSpec="+childWidthMeasureSpec
                        +", childHeightMeasureSpec="+childHeightMeasureSpec
                        +", childMeasuredWidth="+childMeasuredWidth
                        +", childMeasuredHeight="+childMeasuredHeight);

                if (childMeasuredWidth + lineWidthUsed + mHorizontalSpacing > viewGroupWidth) {
                    Log.i(TAG, "childView==>i="+i+", 需要换行了");
                    //如果需要换行的情况,一旦换行,就可以判断当前行需要的宽和高了,所以需要记录下来
                    mAllLineViews.add(lineViews);
                    mLineHeights.add(lineHeight);

                    //父View需要的宽度
                    parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
                    //父View需要的高度
                    parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;

                    //重新创建下一行的View集合,重置已用的行宽度和行高
                    lineViews = new ArrayList<>();
                    lineWidthUsed = 0;
                    lineHeight = 0;
                }
                //view 是分行layout的,所以要记录每一行有哪些view,这样可以方便layout布局
                lineViews.add(childView);
                //每行都会有自己的宽和高(每加一个View,就会执行一遍子view宽度和横向空格加的操作)
                lineWidthUsed = lineWidthUsed + childMeasuredWidth + mHorizontalSpacing;
                //每一行的高度取子View高度的最大值
                lineHeight = Math.max(lineHeight, childMeasuredHeight);

                if (i == childCount - 1) {
                    mAllLineViews.add(lineViews);
                    mLineHeights.add(lineHeight);

                    //父View需要的宽度
                    parentNeededWidth = Math.max(parentNeededWidth, lineWidthUsed + mHorizontalSpacing);
                    //父View需要的高度
                    parentNeededHeight = parentNeededHeight + lineHeight + mVerticalSpacing;
                }
            }
        }

        //根据子View的测量结果,来测量ViewGroup自己的宽高
        int viewGroupRealWidth  = (viewGroupWidthMode == MeasureSpec.EXACTLY) ? viewGroupWidth : parentNeededWidth;
        int viewGroupRealHeight  = (viewGroupHeightMode == MeasureSpec.EXACTLY) ? viewGroupHeight : parentNeededHeight;
        //测量ViewGroup宽高
        setMeasuredDimension(viewGroupRealWidth, viewGroupRealHeight);

        //测试代码
//        int measuredWidth = getMeasuredWidth();
//        int measuredHeight = getMeasuredHeight();
//        Log.i(TAG, "onMeasure==>ViewGroup测量宽高...measuredWidth="+measuredWidth+", measuredHeight="+measuredHeight);
    }

    /**
     * 遍历每一行,摆放子View
     * @param changed
     * @param l
     * @param t
     * @param r
     * @param b
     */
    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        //onLayout==>changed=true, l=0, t=0, r=1080, b=1990
        Log.i(TAG, "onLayout==>changed="+changed+", l="+l+", t="+t+", r="+r+", b="+b);
        //获取总行数
        int lineCount = mAllLineViews.size();

        int curL = getPaddingLeft();
        int curT = getPaddingTop();

        /**
         * 遍历每一行View
         */
        for (int i = 0; i < lineCount; i++){
            List<View> lineViews = mAllLineViews.get(i);

            //得到每行的行高
            int lineHeight = mLineHeights.get(i);
            /**
             * 遍历一行View,进行摆放位置
             */
            for (int j = 0; j < lineViews.size(); j++){
                View childView = lineViews.get(j);
                int left = curL;
                int top =  curT;

                int right = left + childView.getMeasuredWidth();
                int bottom = top + childView.getMeasuredHeight();
                childView.layout(left,top,right,bottom);
                curL = right + mHorizontalSpacing;
            }
            //每遍历一行,为了下一行摆放View,改变一次top的值
            curT = curT + lineHeight + mVerticalSpacing;
            curL = getPaddingLeft();
        }
    }

    public static int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                Resources.getSystem().getDisplayMetrics());
    }
}

对上述代码中其中的getChildMeasureSpec方法拿来参考

/**
* ViewGroup的getChildMeasureSpec()
*/
public static int getChildMeasureSpec(int spec, int padding, int childDimension) {
        int specMode = MeasureSpec.getMode(spec);
        int specSize = MeasureSpec.getSize(spec);

        int size = Math.max(0, specSize - padding);

        int resultSize = 0;
        int resultMode = 0;

        switch (specMode) {
        // Parent has imposed an exact size on us
        case MeasureSpec.EXACTLY:
            if (childDimension >= 0) {
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size. So be it.
                resultSize = size;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent has imposed a maximum size on us
        case MeasureSpec.AT_MOST:
            if (childDimension >= 0) {
                // Child wants a specific size... so be it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size, but our size is not fixed.
                // Constrain child to not be bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size. It can't be
                // bigger than us.
                resultSize = size;
                resultMode = MeasureSpec.AT_MOST;
            }
            break;

        // Parent asked to see how big we want to be
        case MeasureSpec.UNSPECIFIED:
            if (childDimension >= 0) {
                // Child wants a specific size... let them have it
                resultSize = childDimension;
                resultMode = MeasureSpec.EXACTLY;
            } else if (childDimension == LayoutParams.MATCH_PARENT) {
                // Child wants to be our size... find out how big it should
                // be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            } else if (childDimension == LayoutParams.WRAP_CONTENT) {
                // Child wants to determine its own size.... find out how
                // big it should be
                resultSize = View.sUseZeroUnspecifiedMeasureSpec ? 0 : size;
                resultMode = MeasureSpec.UNSPECIFIED;
            }
            break;
        }
        //noinspection ResourceType
        return MeasureSpec.makeMeasureSpec(resultSize, resultMode);
    }

布局文件如下:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <com.example.nqct.customview.CustomFlowLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="哈哈哈"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="嘿嘿嘿"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="嘎嘎嘎"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/flow_item_text_bg"
            android:text="嘻嘻嘻"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/flow_item_text_bg"
            android:text="呵呵呵"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/flow_item_text_bg"
            android:text="哦哦哦"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/flow_item_text_bg"
            android:text="呱呱呱"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="哗哗哗"/>
    </com.example.nqct.customview.CustomFlowLayout>

</LinearLayout>

引用的TextView的背景drawable文件flow_item_text_bg.xml

<?xml version="1.0" encoding="utf-8"?>
<!--相当于做了一张圆角的图片作为背景图片-->
<shape android:shape="rectangle" xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#FFE7BA"/>
    <padding android:top="8dp" android:right="8dp" android:left="8dp" android:bottom="8dp"/>
    <!--设置圆角-->
    <corners android:radius="25dp"/>
</shape>

————————————————
版权声明:本文为CSDN博主「秃秃秃秃秃秃秃头」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_45716076/article/details/120460575

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

推荐阅读更多精彩内容