自定义标签布局(流布局)

相信大家在做应用的时候经常会遇到显示标签的情况,例如(“上班族,天枰座”这样的),若干个标签长短不一,每个标签之间还有一定的间隙,并且一行显示不下之后,下一个标签显示就需要换行,本篇文章就自定义一个View,来实现所说的这个效果。

首先我们先来看看实现以后是什么样的:

Paste_Image.png

通过这个实际的实现效果我们可以做出下面的分析:
1.每个item的宽度不同
2.行/列之间有间隔
3.数据和布局进行分离,并且布局可以自定义,于是我们考虑利用android的adapter的特性进行实现
4.有自动换行的功能

这个View大概要实现上面的效果,下面就开始撸码:
先建立好这个View,继承自ViewGroup:

public class TagView extends ViewGroup {
}

为了让其使用更加灵活,我们自定义几个属性:

<declare-styleable name="TagView">
        <attr name="maxLine" format="integer" />//最多允许多少行,超过的就不进行显示了
        <attr name="itemSpace" format="dimension" />//每个item之间的宽度(每行的高度,也可以多定义一个高度)
        <attr name="gravity" format="enum">////子View摆放时贴着父布局上边还是下边
            <enum name="top" value="1" />
            <enum name="bottom" value="2" />
        </attr>
    </declare-styleable>

定义好了以后,我们就可以在XML文件里画布局了:

  <com.test.xiao.TagView
            android:id="@+id/gv_tag"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@id/iv_photo"
            android:layout_alignParentLeft="true"
            android:layout_below="@id/tv_content"
            android:layout_toLeftOf="@id/iv_photo"
            app:gravity="bottom"//贴着下边进行摆放
            app:itemSpace="3dp"
            app:maxLine="2" />

item的布局如下:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/tv_item"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/shape_main_tag_sub"//橙色的背景
    android:ellipsize="end"
    android:gravity="center"
    android:maxLines="1"
    android:paddingBottom="1dp"
    android:paddingLeft="2dp"
    android:paddingRight="2dp"
    android:paddingTop="1dp"
    android:text="TextView01"
    android:textColor="@color/white"
    android:textSize="@dimen/ss_small_textSize" />

好了,这些准备工作完成以后,我们就可以开始实现View的功能了,首先定义好相关变量并进行初始化:

public class TagView extends ViewGroup {
private int itemSpace = 0;//item之间的间距
    private Adapter mAdapter;//获取数据和子item的适配器,这个adapter就是android原生提供的adapter
    private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(项目中暂时未用到垂直需求,所以暂时不需要)
    private SparseArray<SparseArray<View>> views;//用于记录第几行,第几个item
    private SparseArray<Integer> maxHeights;//记录每行的最大高度
    private int maxLine;//设置最大的行数
    private int gravity;//子View贴着上边还是下边(默认上边),1是上边,2是下边
public TagView(Context context) {
        super(context);
        init(null);
    }

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

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

    private void init(AttributeSet attributeSet) {
        views = new SparseArray<>();
        maxHeights = new SparseArray();
        if (attributeSet == null) {
            itemSpace = Utils.dp2px(getContext(), 5);
            maxLine = 10;// 默认最大行数
        } else {
            TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
            itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
            gravity = array.getInt(R.styleable.TagView_gravity, 1);
            maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
            array.recycle();
        }
    }
}

接下来我们需要在onMeasure里通过adapter获取到相关的view,并且测量出每个view的宽度和高度,根据宽度来计算出我们需要多少行,每行分别需要列来放这些item:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int needWidth = MeasureSpec.getSize(widthMeasureSpec);
        int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
        int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
        int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
        if (mAdapter != null && mAdapter.getCount() > 0) {//如果adapter没有数据,则不进行绘制,直接调用super.onMeasure
            View child = null;//从adaper中获取的子View
            int childWidth = 0;//子View的宽度
            int currentLineWidth = 0;//当前行的总宽度
            int currentLine = 0;//当前是第几行
            int currentElement = 0;//当前行的第几个元素
            int maxHeight = 0;//当前行的最大高度
            int resultHeihgt = 0;//通过子View的测量情况最终算出来的父View高度
            boolean isMaxLine = false;//当前是否已经到达最大行
            for (int i = 0; i < mAdapter.getCount(); i++) {//通过adapter来遍历测量所有的子View
                if (currentLine == maxLine) {//到达最大行数时,如果还有下一行,我们就不进行显示了
                    isMaxLine = true;
                    break;
                }
                child = mAdapter.getView(i, null, this);
                measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//获取子控件大小
                childWidth = child.getMeasuredWidth();
                if (currentLineWidth == 0) {//已经到达新的一行
                    views.put(currentLine, new SparseArray<>());//新建一个用来存放新的一行元素的集合
                }
                if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要换行
                    resultHeihgt += maxHeight + itemSpace;
                    maxHeights.put(currentLine, maxHeight);
                    currentLine++;
                    currentLineWidth = 0;
                    currentElement = 0;
                    i--;
                } else {
                    if (child.getMeasuredHeight() > maxHeight) {
                        maxHeight = child.getMeasuredHeight();//计算本行的最大高度,在layout时,每行的高度就以最大高度为准
                    }
                    views.get(currentLine).put(currentElement, child);//在测量完了,并且分析好这个元素的位置后,将其放入集合中,待之后onLayout时进行摆放
                    currentElement++;
                    currentLineWidth += itemSpace + childWidth;
                }
            }
            if (resultHeihgt == 0) {//当前item仅有一行
                resultHeihgt = maxHeight;
                maxHeights.put(0, maxHeight);
            } else {//当前item不止一行,且未到达最大行数限制,到这里时,需要补齐最后一行的高度数据
                if (!isMaxLine) {
                    resultHeihgt += maxHeight;//
                    maxHeights.put(currentLine, maxHeight);
                }
            }
            setMeasuredDimension(needWidth, resultHeihgt);//设置最终的宽高
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

通过onMeasure,我们通过每个item的宽高计算出了TagView的宽高,要显示的行数,每行的高度以及每行的元素及其所处的位置(存放到了views中),通过这些得到的内容,接下来我们就要在onLayout中计算出每个item应该摆放的具体位置了:

//在这个方法里我们要确定每个View摆放的位置
@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mAdapter != null && mAdapter.getCount() > 0) {
            View view;//当前要进行摆放的子View
            View lastView;//当前摆放的子View左边的View
            int childLeft, childRight, childTop, childBottom;
            for (int i = 0; i < views.size() && i < maxLine; i++) {//这个循环用来循环行数
                for (int j = 0; j < views.get(i).size(); j++) {//这个循环用来循环每行的列数
                    view = views.get(i).get(j);//第i行第j个元素
                    childLeft = 0;
                    for (int k = 0; k < j; k++) {//通过前面所有View的宽度相加,得到当前子View的left位置
                        lastView = views.get(i).get(k);
                        childLeft += lastView.getMeasuredWidth() + itemSpace;
                    }
                    childRight = childLeft + view.getMeasuredWidth();
//确定子View上下的位置,根据gravity的不同(1是靠近父View顶部摆放,2是靠近父View底部摆放)
                    if (gravity == 1) {
                        childTop = 0;
                        for (int k = 0; k < i; k++) {//通过前面所有高度行数相加,得到最终的上边位置
                            childTop += maxHeights.get(k) + itemSpace;
                        }
                    } else {
                        childTop = b - t;//b-t为最后一行的底部
                        for (int k = views.size() - 1 - i; k >= 0; k--) {//第一行的top位置是从最底部算起,后面所有行的高度+自身的高度值+行与行之间的空隙
                            childTop -= (maxHeights.get(k) + itemSpace);
                        }
                        childTop += itemSpace;//这里要加上多减去的空间
                    }

                    childBottom = childTop + view.getMeasuredHeight();
                    view.layout(childLeft, childTop, childRight, childBottom);
                    addView(view);
                }
            }
        }
    }

对于adapter,我们要给出一个可以进行设置的方法:

public void setAdapter(Adapter adapter) {
        mAdapter = adapter;
        invalidate();
    }

使用的时候,我们这样使用(采用的是效果图中的数据):

String[] testTags = new String[]{"ssssss", "大家得人生", "ssdsjdj", "我们和小李都有", "放下一切", "大大大大大大多多"};
public void onCreate(Bundle saveInstanceStates){
...
TagView gv_tag = findViewById(R.layout.gv_tag);
gv_tag.setAdapter(new ArrayAdapter<>(context, R.layout.item_main_grid_sub_tag, R.id.tv_item, data.getTags()));//采用adapter方式比较灵活
...
}

完整代码如下:

/**
 * Created by LiXiaoSong on 2017/7/10.
 * 自定义Tagview,用于显示流布局
 */

public class TagView extends ViewGroup {
    private int itemSpace = 0;//item之间的间距
    private Adapter mAdapter;//这里传入的adapter仅仅使用了其简单的功能
    private int ORIENTATION;//方向值,可以取VERTICAL,HORIZONTAL(项目中暂时未用到垂直需求,所以暂时不需要)
    private SparseArray<SparseArray<View>> views;//用于记录第几行,第几个item
    private SparseArray<Integer> maxHeights;//记录每行的最大高度
    private int maxLine;//设置最大的行数
    private int gravity;//子View贴着上边还是下边(默认上边),1是上边,2是下边

    public TagView(Context context) {
        super(context);
        init(null);
    }

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

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

    private void init(AttributeSet attributeSet) {
        views = new SparseArray<>();
        maxHeights = new SparseArray();
        if (attributeSet == null) {
            itemSpace = Utils.dp2px(getContext(), 5);
            maxLine = 10;// 默认最大行数
        } else {
            TypedArray array = getContext().obtainStyledAttributes(attributeSet, R.styleable.TagView);
            itemSpace = array.getDimensionPixelSize(R.styleable.TagView_itemSpace, Utils.dp2px(getContext(), 10));
            gravity = array.getInt(R.styleable.TagView_gravity, 1);
            maxLine = array.getInt(R.styleable.TagView_maxLine, 10);
            array.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int needWidth = MeasureSpec.getSize(widthMeasureSpec);
        int needHeihgt = MeasureSpec.getSize(heightMeasureSpec);
        int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(needWidth, MeasureSpec.getMode(widthMeasureSpec));
        int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(needHeihgt, MeasureSpec.getMode(heightMeasureSpec));
        if (mAdapter != null && mAdapter.getCount() > 0) {
            View child = null;
            int childWidth = 0;
            int currentLineWidth = 0;
            int currentLine = 0;//当前行数
            int currentElement = 0;
            int maxHeight = 0;//当前行数最大高度
            int resultHeihgt = 0;
            boolean isMaxLine = false;
            for (int i = 0; i < mAdapter.getCount(); i++) {//这里用来存放子View的元素
                if (currentLine == maxLine) {
                    isMaxLine = true;
                    break;
                }
                child = mAdapter.getView(i, null, this);
                measureChild(child, parentWidthMeasureSpec, parentHeightMeasureSpec);//获取子控件大小
                childWidth = child.getMeasuredWidth();
                if (currentLineWidth == 0) {//新的一行
                    views.put(currentLine, new SparseArray<>());
                }
                if (childWidth + itemSpace + currentLineWidth > needWidth) {//需要换行
                    resultHeihgt += maxHeight + itemSpace;
                    maxHeights.put(currentLine, maxHeight);
                    currentLine++;
                    currentLineWidth = 0;
                    currentElement = 0;
                    i--;
                } else {
                    if (child.getMeasuredHeight() > maxHeight) {
                        maxHeight = child.getMeasuredHeight();
                    }
                    views.get(currentLine).put(currentElement, child);
                    currentElement++;
                    currentLineWidth += itemSpace + childWidth;
                }
            }
            if (resultHeihgt == 0) {//当前item仅有一行
                resultHeihgt = maxHeight;
                maxHeights.put(0, maxHeight);
            } else {//如果不是,补齐最后一行的数据
                if (!isMaxLine) {
                    resultHeihgt += maxHeight;//
                    maxHeights.put(currentLine, maxHeight);
                }
            }
            setMeasuredDimension(needWidth, resultHeihgt);
        } else {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }

    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        if (mAdapter != null && mAdapter.getCount() > 0) {
            View view;
            View lastView;//它前面的View
            int childLeft, childRight, childTop, childBottom;
            for (int i = 0; i < views.size() && i < maxLine; i++) {
                for (int j = 0; j < views.get(i).size(); j++) {
                    view = views.get(i).get(j);//第i行第j个元素
                    childLeft = 0;
                    for (int k = 0; k < j; k++) {//通过前面所有View的宽度相加,得到最终的左边位置
                        lastView = views.get(i).get(k);
                        childLeft += lastView.getMeasuredWidth() + itemSpace;
                    }
                    childRight = childLeft + view.getMeasuredWidth();
                    childTop = 0;
                    if (gravity == 1) {
                        for (int k = 0; k < i; k++) {//通过前面所有高度行数相加,得到最终的上边位置
                            childTop += maxHeights.get(k) + itemSpace;
                        }
                    } else {
                        childTop = b - t;//设置一个底部
                        for (int k = views.size() - 1 - i; k >= 0; k--) {//通过前面所有高度行数相加,得到最终的上边位置
                            childTop -= (maxHeights.get(k) + itemSpace);
                        }
                        childTop += itemSpace;
                    }

                    childBottom = childTop + view.getMeasuredHeight();
                    view.layout(childLeft, childTop, childRight, childBottom);
                    addView(view);
                }
            }
        }
    }

    public void setAdapter(Adapter adapter) {
        mAdapter = adapter;
        invalidate();
    }
}

本文到此结束,如果有什么问题,欢迎一起讨论。

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,566评论 25 707
  • 树雄心创大业江山添锦绣,立壮志写春秋日月耀光华。水惟向下方成海,山不吟高可及天一杯土,尚巍然,问他铜雀荒台,何处寻...
    每个人的孟母堂阅读 785评论 1 1
  • “崔佳儿!”“兰玉石!”“吴优越!”“王府依!”柯老师。我失败了,竞选失败了!我的好友兰玉石却入选了。 在Mun国...
    白嘉浅阅读 295评论 0 0
  • 今天应单位的工作部署,写了一篇党支部的《学习十九大心得体会》。现在以个人的名义,继续写出心得体会!我可以...
    老区游子阅读 594评论 0 3
  • 捧起《失乐园》,缘于与挚友分享《挪威的森林》读后感后的推荐,时隔半年,好奇心一直驱使着我去捧读,入手很久,终于...
    追寻真我阅读 210评论 0 2