Android开发之流式布局(实现热门标签效果)

又到了美好周末时间,由于更新博客的时间总是断断续续,突然有个想法,想对博客进行每十天一更,不知道能不能合理的安排出时间来,尝试着做看看吧。
由于公司产品的迭代更新,这次UI设计师做出了个类似简书热门标签页的效果,虽然谷歌官方已经提供了一个很友好的弹性布局FlexboxLayout传送门可以帮助我们实现这一效果,但是强迫症的我还是想要自己实现一波。

首先先来看下简书上的实现效果:

《Android开发之流式布局(实现热门标签效果)》 简书首页热门标签效果

下面是我自己仿写的效果:

《Android开发之流式布局(实现热门标签效果)》 流式布局实现热门标签效果

实现思路:
首先我们可以把这一标签页的整体看成一个容器,然后容器内有许多小控件(TextView,Button,ImageView等),再来这些小控件成水平排列并且会根据自身的布局大小来决定是否换行。

我们很容易可以联想到:
容器:自定义ViewGroup
小控件:原生自带的控件
水平排列并根据自身大小换行:需要测量比对,布置位置

关于ViewGroup:

关于测量:
由于在容器ViewGroup里装载的是原生控件(TextView,Button,ImageView等),所以对于原生控件的属性(内部对齐方式,缩放方式,内边距等)我们不需要去做另外的处理,但这里涉及到了一个控件与控件之间的距离(外边距margin),所以我们需要让ViewGroup去认识这个标签,在原生的ViewGroup里是不支持margin的,ViewGroup里有两个内部类分别是ViewGroup.LayoutParams和ViewGroup. MarginLayoutParams,ViewGroup. MarginLayoutParams继承于ViewGroup.LayoutParams也扩展了支持的属性,也就是magin属性,所以我们需要重写generateLayoutParams方法让其返回MarginLayoutParams对象

    /**
     * 指定ViewGroup的LayoutParams
     *
     * @param attrs
     * @return
     */
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

再来就是关于测量了,在ViewGroup里测量是在onMeasure方法里实现的,由于LinearLayout和RelativeLayout等这些布局是继承于ViewGroup的,这些布局摆放控件的方式是不一样的,比如LinearLayout是呈线性摆放的,RelativeLayout是呈叠加摆放的,所以测量的方式也是不一样的,所以ViewGroup并没有给我们做好子View的测量工作,而是让我们去重写onMeasure方法进行测量,一个ViewGroup除非指定它的宽高精确值或者让其充满match_parent,否则它是不知道自身大小应该是多少的,所以我们需要对包含在ViewGroup里的子View进行逐个测量,然后累加宽高来确定ViewGroup的宽高值。

       /**
        * Measure specification mode: The parent has not imposed any constraint
        * on the child. It can be whatever size it wants.
        */
       public static final int UNSPECIFIED = 0 << MODE_SHIFT;

       /**
        * Measure specification mode: The parent has determined an exact size
        * for the child. The child is going to be given those bounds regardless
        * of how big it wants to be.
        */
       public static final int EXACTLY     = 1 << MODE_SHIFT;

       /**
        * Measure specification mode: The child can be as large as it wants up
        * to the specified size.
        */
       public static final int AT_MOST     = 2 << MODE_SHIFT;

谷歌官方给我们提供了三种测量模式:
EXACTLY:精确大小,可以让ViewGroup宽高为我们的指定值或者是充满match_parent
AT_MOST:给出限定大小,子View可以在ViewGroup的允许范围内伸展大小
UNSPECIFIED:不指定限制,子View想要多大就给多大(几乎很少使用)

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

我们可以在onMeasure方法里通过MeasureSpec.getMode和MeasureSpec.getSize得到对应的测量模式和测量尺寸,当模式为EXACTLY的时候,我们就可以直接应用所测量的尺寸,但如果是其他模式,那么我们就只能自己去测量子View的尺寸了。

关于布局:

@Override
    protected abstract void onLayout(boolean changed,
            int l, int t, int r, int b);

在自定义ViewGroup中提供了一个抽象方法onLayout需要我们对其实现,在这里我们可以对子View的位置进行确定排列,ViewGroup通过onLayout 方法来确定View在容器中的位置,View通过layout方法来确认自己在父容器中的位置,l,t,r,b参数分别代表left,top,right,bottom,也就是左上和右下。

好了,由于篇幅的限制,有些东西不能讲的太细,有不清楚的朋友自行查阅相关资料补充吧。

具体实现:

我们开始来分析下今天要实现的效果:
1、首先我们需要去自定义一个ViewGroup,然后再其内包含各种子控件(这里是多个TextView),就好比LinearLayout包含子控件一样。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical">


    <com.lcw.view.flowlayout.FlowLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="4dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="欧美影视"
            android:textColor="@color/colorAccent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="婚姻育儿"
            android:textColor="@color/colorAccent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="散文"
            android:textColor="@color/colorAccent" />


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="程序员"
            android:textColor="@color/colorAccent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="大学生生活"
            android:textColor="@color/colorAccent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="运营互助帮"
            android:textColor="@color/colorAccent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="设计"
            android:textColor="@color/colorAccent" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="8dp"
            android:background="@drawable/shape_tv_blue"
            android:padding="5dp"
            android:text="读书"
            android:textColor="@color/colorAccent" />

    </com.lcw.view.flowlayout.FlowLayout>


</LinearLayout>

2、然后我们在onMeasure里通过getChildCount拿到子View的个数,并利用measureChild对子View进行遍历测量,通过测量宽高的累加后得到再通过setMeasuredDimension设置ViewGroup的宽高。

    /**
     * 测量所有子View大小,确定ViewGroup的宽高
     *
     * @param widthMeasureSpec
     * @param heightMeasureSpec
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        //由于onMeasure会执行多次,避免重复的计算控件个数和高度,这里需要进行清空操作
        mLineViews.clear();
        mLineHeight.clear();

        //获取测量的模式和尺寸大小
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);


        //记录ViewGroup真实的测量宽高
        int viewGroupWidth = 0;
        int viewGroupHeight = 0;

        if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) {
            viewGroupWidth = widthSize;
            viewGroupHeight = heightSize;
        } else {
            //当前所占的宽高
            int currentLineWidth = 0;
            int currentLineHeight = 0;

            //用来存储每一行上的子View
            List<View> lineView = new ArrayList<View>();
            int childViewsCount = getChildCount();
            for (int i = 0; i < childViewsCount; i++) {
                View childView = getChildAt(i);
                //对子View进行测量
                measureChild(childView, widthMeasureSpec, heightMeasureSpec);
                MarginLayoutParams marginLayoutParams = (MarginLayoutParams) childView.getLayoutParams();
                int childViewWidth = childView.getMeasuredWidth() + marginLayoutParams.leftMargin + marginLayoutParams.rightMargin;
                int childViewHeight = childView.getMeasuredHeight() + marginLayoutParams.topMargin + marginLayoutParams.bottomMargin;

                if (currentLineWidth + childViewWidth > widthSize) {
                    //当前行宽+子View+左右外边距>ViewGroup的宽度,换行
                    viewGroupWidth = Math.max(currentLineWidth, widthSize);
                    viewGroupHeight += currentLineHeight;
                    //添加行高
                    mLineHeight.add(currentLineHeight);
                    //添加行对象
                    mLineViews.add(lineView);

                    //new新的一行
                    lineView = new ArrayList<View>();
                    //添加行对象里的子View
                    lineView.add(childView);
                    currentLineWidth = childViewWidth;

                } else {
                    //当前行宽+子View+左右外边距<=ViewGroup的宽度,不换行
                    currentLineWidth += childViewWidth;
                    currentLineHeight = Math.max(currentLineHeight, childViewHeight);
                    //添加行对象里的子View
                    lineView.add(childView);
                }

                if (i == childViewsCount - 1) {
                    //最后一个子View的时候
                    //添加行对象
                    mLineViews.add(lineView);
                    viewGroupWidth = Math.max(childViewWidth, viewGroupWidth);
                    viewGroupHeight += childViewHeight;
                    //添加行高
                    mLineHeight.add(currentLineHeight);

                }
            }
        }
        setMeasuredDimension(viewGroupWidth, viewGroupHeight);
    }

3、然后我们在onLayout里去设置子View所在的位置。

    /**
     * 设置ViewGroup里子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) {


        int left = 0;
        int top = 0;
        //一共有几行
        int lines = mLineViews.size();
        for (int i = 0; i < lines; i++) {
            //每行行高
            int lineHeight = mLineHeight.get(i);
            //行内有几个子View
            List<View> viewList = mLineViews.get(i);
            int views = viewList.size();

            for (int j = 0; j < views; j++) {
                View view = viewList.get(j);
                MarginLayoutParams marginLayoutParams = (MarginLayoutParams) view.getLayoutParams();
                int vl = left + marginLayoutParams.leftMargin;
                int vt = top + marginLayoutParams.topMargin;
                int vr = vl + view.getMeasuredWidth();
                int vb = vt + view.getMeasuredHeight();
                view.layout(vl, vt, vr, vb);
                left += view.getMeasuredWidth() + marginLayoutParams.leftMargin + marginLayoutParams.rightMargin;
            }
            left = 0;
            top += lineHeight;

        }
    }

说明:
1、List<List<View>>对象,View表示子View,List<View>表示每行有多少子View,List<List<View>>表示有几行。
2、List<Integer>对象,用来记录每行的高度。
3、在onMeasure测量方法中,我们在测量每个子View的宽度时把宽度进行累加(包含子View的左右外边距),当累加的宽度比最大宽度宽时,需要进行换行,同时在测量每个子View的时候需要记录它的高度,行高取最大高度的那个子View。
4、这里还可以做一些扩展的补充,比如设置标签的点击监听事件,解决ViewGroup内边距等,随后会在Github库上更新。

源码下载:

这里附上源码地址(欢迎Star,欢迎Fork):源码下载

    原文作者:李晨玮
    原文地址: https://www.jianshu.com/p/05954091c650
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞