自定义控件篇 — 标签流式布局TagFlowLayout

本篇主要内容:从0到1写一个流式布局TagFlowLayout

1 通过本篇可以了解什么

  • 继承至ViewGroup的组件如何编写onMeasureonLayout方法;
  • Viewmargin值是如何在onMeasureonLayout中使用的;
  • 流式布局的基本原理。

2 继承ViewGroup的组件到底意味着什么

首先,ViewGroup是一个组件容器,它自身没有进行任何测量和布局,但是它提供了一系列测量子View的方法,方便我们调用。

再者,我们需要在继承ViewGroup组件中的测量方法中进行子View控件的测量。

onMeasure中确定各个View的大小以及onLayout中需要的摆放参数,onLayout中进行摆放。

paddingmargin值需要在测量和摆放时加入计算中,onMeasure中大部分考虑的是margin,onLayout中考虑paddingmargin值。

3 实现过程

废话不多说,先看效果图:

图1

3.1 创建控件

这一步相对简单,就不做过多说明,代码如下:

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

    public TagFlowLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

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

    private void init() {

    }
}

3.2 onMeasure方法实现过程

先用图说明一下measure逻辑流程,其实也很简单。

图2

由上图可知,我们有两个目标:

  • 其一,遍历并计算每个子View
  • 其二,找出超出屏幕位置的View,并进行换行。
3.2.1 遍历并计算每个View
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        LogUtils.d("onMeasure: " + onMeasureCount++);

        int childCount = getChildCount();

        for (int i = 0; i < childCount; i++) {

        }

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

    }

接下来开始对每个子View进行测量,ViewGroup给我们提供了测量子View的方法measureChildWithMargins()于是就有了如下代码:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    LogUtils.d("onMeasure: " + onMeasureCount++);

    int childCount = getChildCount();

    for (int i = 0; i < childCount; i++) {
        View child = getChildAt(i);

        measureChildWithMargins();
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

但是发现measureChildWithMargins有五个参数,如下:

protected void measureChildWithMargins(View child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed)
  • 第一个参数child,就是我们需要测量的View
  • 第二个参数parentWidthMeasureSpec,这是我们传递给子view对于宽度的建议;
  • 第三个参数是指父控件在水平方向上已使用的宽度,有可能是其他子 view使用的空间;
  • 第四个和第五个参数与第二个、三个参数雷同,只是是竖直方向。

知道这几个参数的意义后,于是我们就可以在计算子view时传递相应的参数值。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    LogUtils.d("onMeasure: " + onMeasureCount++);

    int childCount = getChildCount();

    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);
        measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, 0);
    }
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

到这里我们应该会有个疑问:widthUsed和heightUsed这两个参数为什么是0?

原因如下:

  • 因为如果把已用的空间传入这个参数,那么有可能会导致影响子view的测量结果;
    至于为什么会影响子 view的测量结果,我们看看源码:
protected void measureChildWithMargins(View child,
        int parentWidthMeasureSpec, int widthUsed,
        int parentHeightMeasureSpec, int heightUsed) {
    final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

    // widthUsed会作为getChildMeasureSpec方法中padding参数值的一部分进入到view的MeasureSpec参数的计算中去,
    // 所以父view的建议有可能会影响子view最终大小
    final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec,
            mPaddingLeft + mPaddingRight + lp.leftMargin + lp.rightMargin
                    + widthUsed, lp.width);
    final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec,
            mPaddingTop + mPaddingBottom + lp.topMargin + lp.bottomMargin
                    + heightUsed, lp.height);

    child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
}
  • 而我们所想要的效果是子View按照自己的测量方式测量出自己大小,空间不足,另起一行,不能约束子View

好了,上面查看了部分源码进行分析,我们继续回归主题。

3.2.2 找出超出屏幕的View,并且进行换行。

基本思路如下:

  • 定义相应数据结构;
  • 同一行宽度累加;
  • 与控件TagFlowLayout本身宽度进行比较查看是否超出当前行。

由图2可知,其实就是计算出每一行都有哪些View,最容易想到的数据结构就是:List<List<View>>。外层List表示有多少行,里层List表示每一行多少个子View

另外,需要一个临时变量记录住当前子View已经使用的空间,定义为currentLineTotalWidth

还需知道控件本身的宽度widthSize,为了和当前所有View已占用的空间进行宽度对比,代码如下:

// 所有的view
private List<List<View>> mAllViews;
// 每一行的View
private List<View> mRowViewList;

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    LogUtils.d("onMeasure: " + onMeasureCount++);
    mAllViews.clear();
    mRowViewList.clear();

    // TagFlowLayout的宽度
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    // 当前行遍历过程中子View的宽度累加
    // 也可以当成当前行已使用的空间
    int currentLineTotalWidth = 0;

    int childCount = getChildCount();

    for (int i = 0; i < childCount; i++) {
        View childView = getChildAt(i);

        measureChildWithMargins(childView, widthMeasureSpec, 0, heightMeasureSpec, 0);
        // 获取当前子View的宽度
        int childWidth = childView.getMeasuredWidth();
        // 一行已经超出,另起一行
        if (currentLineTotalWidth + childWidth > widthSize) {
            // 重置当前currentLineTotalWidth 
            currentLineTotalWidth = 0;
            // 添加当前行的所有子View
            mAllViews.add(mRowViewList);
            // 另起一行,需要新开辟一个集合
            mRowViewList = new ArrayList<>();
            mRowViewList.add(childView);
            // 最后一个控件单独一行
            if (i == (childCount - 1)) {
                mAllViews.add(mRowViewList);
            }        
        } else {
            // 没换行,继续累加
            currentLineTotalWidth += childView.getMeasuredWidth();
            mRowViewList.add(childView);
            // 最后一个view并且没有超出宽度
            if (i == (childCount - 1)) {
                mAllViews.add(mRowViewList);
            }
        }
    }

    super.onMeasure(widthMeasureSpec, heightMeasureSpec);

}

接下来,我们的目标是算出控件的宽高,并且设置进setMeasuredDimension方法中。

而最终的宽度就是所有行中最大的那个宽,所以每次新增加一个控件就可以比较两个值中的最大值。而高度是累加,在每次换行时都加上上一行的高度。

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    // 省略无关代码 ...

    // 测量最终的宽度
    int selfMeasureWidth = 0;
    // 测量最终的高度
    int selfMeasureHeight = 0;
    // 当前行的最大高度
    int currentLineMaxHeight = 0;
    
    if (currentLineTotalWidth + childWidth > widthSize) {
        selfMeasureWidth = Math.max(selfMeasureWidth, currentLineTotalWidth);
        selfMeasureHeight += currentLineMaxHeight;
        currentLineMaxHeight = childHeight + marginLayout.topMargin + marginLayout.bottomMargin;
        if (i == (childCount - 1)) {
            selfMeasureHeight += currentLineMaxHeight;
        }
    } else {
        currentLineMaxHeight = Math.max(currentLineMaxHeight, (childHeight + marginLayout.topMargin + marginLayout.bottomMargin));
        currentLineTotalWidth += childView.getMeasuredWidth();
        selfMeasureWidth = Math.max(selfMeasureWidth, currentLineTotalWidth);
        if (i == (childCount - 1)) {
            selfMeasureHeight += currentLineMaxHeight;
        }
    }

    setMeasuredDimension(selfMeasureWidth, selfMeasureHeight);
}

到此为止,控件的onMeasure方法就已基本完成。

3.3 onLayout方法实现过程

接下来就是摆放位置,分别从总的控件集合中取出相应的控件,然后进行摆放,坐标位置就是控件的上下左右四个点。

在横向上,如果一行有多个控件,则进行宽度的累加来确定其他子View的位置。

在纵向上,主要就是确定每一行的起始高度位置

而针对这个起始高度位置,我们在测量onMeasure过程中,会保存一个高度集合mHeightList,记录每一行最大高度,将在onLayout中使用。

主要代码如下:

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        LogUtils.d("onLayout: " + onLayoutCount++);

        int alreadyUsedWidth;
        // 摆放的开始高度位置
        int beginHeight = 0;
        int left, top, right, bottom;
        // mHeightList存放了每一行的最大高度
        if (mHeightList.size() != mAllViews.size()) {
            LogUtils.e("mHeightList's size is not equal to mAllViews's size");
            return;
        }

        for (int i = 0; i < mAllViews.size(); i++) {
            List<View> rowList = mAllViews.get(i);
            if (rowList == null) continue;
            // 每一行开始的摆放的位置alreadyUsedWidth,累加后,成为每一行已经使用的空间
            alreadyUsedWidth = getPaddingLeft();
            beginHeight += mHeightList.get(i);

            if (i == 0) {
                beginHeight += getPaddingTop();
            }

            for (int j = 0; j < rowList.size(); j++) {
                View childView = rowList.get(j);
                MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();

                left = alreadyUsedWidth + params.leftMargin;
                right = left + childView.getMeasuredWidth();
                top = beginHeight + params.topMargin;
                bottom = top + childView.getMeasuredHeight();

                childView.layout(left, top, right, bottom);

                alreadyUsedWidth = right;
            }
        }
    }

3.4 关于实现子 View MarginLayout的布局

默认情况下,ViewGroup的LayoutParams为ViewGroup.LayoutParams,如需要使用margin_left这类属性操作,需要重写generateLayoutParams方法。

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

综上,就是流式布局的基本原理。如有错误,欢迎指出讨论。

4 写在最后

在这个微凉的早餐终于完成了这篇文章的编写,前几天和一朋友喝茶聊天,聊到了文章创作其实也是一种服务,服务于其他有需求的人。而服务意识又是打开另一扇大门的一种重要品质,未来希望能创作更多更好的服务。

如果喜欢,欢迎点赞与分享,创作不易,你的支持将是最好的回馈。

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

推荐阅读更多精彩内容