Android 自定义ViewGroup——FlowLayout流式标签

最近一直在学习自定义View和自定义ViewGroup的东西,今天没事干就研究了一下FlowLayout,记录下实现步骤,参考自鸿洋博客

AndroidStudio使用

在根projcet的build.gradle中添加.

maven { url 'https://jitpack.io' }

在项目的build.gradle添加:

compile 'com.github.superSp:FlowLayout:1.0'

github有源码查看

效果图 自适应

图片.png

效果图 固定大小

图片.png

使用方法——静态添加

<lsp.com.library.FlowLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        style="@style/text_flag_01"
        android:text="Welcome" />

    <TextView
        style="@style/text_flag_01"
        android:text="IT工程师" />

    <TextView
        style="@style/text_flag_01"
        android:text="学习ing" />

    <TextView
        style="@style/text_flag_01"
        android:text="恋爱ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="恋爱ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="挣钱ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="努力ing" />

    <TextView
        style="@style/text_flag_02"
        android:text="I thick i can" />

</lsp.com.library.FlowLayout>

style文件:

  <style name="text_flag_01">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">5dp</item>
        <item name="android:background">@drawable/flag_01</item>
    </style>

drawable文件:

样式1(flag_01)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#7690A5"/>

    <corners android:radius="5dp"/>

    <padding android:bottom="2dp"
        android:left="2dp"
        android:right="2dp"
        android:top="2dp"/>
</shape>

样式2(flag_02)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#E7E7E7" >
    </solid>
    <corners
        android:radius="30dp"
        />

    <padding
        android:bottom="2dp"
        android:left="10dp"
        android:right="10dp"
        android:top="2dp" />
</shape>

按自己喜好设置就行~~

使用方法——动态添加


        FlowLayout flowLayout = new FlowLayout(this);

        flowLayout.initData(Arrays.asList("Welcome","IT工程师","学习ing","恋爱ing"
        ,"挣钱ing","努力ing","I thick i can"));

        setContentView(flowLayout);

initData方法

public void initData(List<String> list)
public void initData(List<String> list, int margin, int drawable) 

添加点击事件

 flowLayout.setOnTabClickListener(new FlowLayout.IOnTabClickListener() {

            @Override
            public void onTabClick(int position, TextView textView) {
                Toast.makeText(Test.this,position+" "+textView.getText(),Toast.LENGTH_SHORT).show();
            }
        });
        setContentView(flowLayout);

实现思路

构造方法
    public FlowLayout(Context context) {
        this(context, null);
    }

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

    public FlowLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
子view支持margin属性
 @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(), attrs);
    }

onMeasure方法

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        //测量子view的大小
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        //最终的宽和高
        int width = 0;
        int height = 0;
        //记录每一行的宽和高
        int lineWidth = 0;
        //子view数量
        int cCount = getChildCount();
        View cView;
        MarginLayoutParams params;
        int cWidth, cHeight;

        for (int i = 0; i < cCount; i++) {
            cView = getChildAt(i);
            params = (MarginLayoutParams) cView.getLayoutParams();
            cWidth = cView.getMeasuredWidth() + params.leftMargin + params.rightMargin;
            cHeight = cView.getMeasuredHeight() + params.topMargin + params.bottomMargin;

            ViewBean viewBean = new ViewBean();
          
            if (lineWidth + cWidth < widthSize) {

                lineWidth += cWidth;

                height = Math.max(height, cHeight);

                width = Math.max(lineWidth, width);

            } else {

                width = Math.max(lineWidth, width);

                height += cHeight;

                lineWidth = cWidth;

            }

            viewBean.setLeft(lineWidth - cWidth + params.leftMargin);
            viewBean.setTop(height - cHeight + params.topMargin);
            viewBean.setRight(lineWidth - params.rightMargin);
            viewBean.setBottom(height - params.bottomMargin);

            list.add(viewBean);

        }
        setMeasuredDimension(widthMode == MeasureSpec.EXACTLY ? widthSize : width, heightMode == MeasureSpec.EXACTLY ? heightSize : height);
    }
onLayout方法
 @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int cCount = getChildCount();
        for (int i = 0; i < cCount; i++) {
            getChildAt(i).layout(list.get(i).getLeft(), list.get(i).getTop(), list.get(i).getRight(), list.get(i).getBottom());
        }

    }
ViewBean方法
private class ViewBean {
        private int left;
        private int right;
        private int top;
        private int bottom;

        public int getLeft() {
            return left;
        }

        public void setLeft(int left) {
            this.left = left;
        }

        public int getRight() {
            return right;
        }

        public void setRight(int right) {
            this.right = right;
        }

        public int getTop() {
            return top;
        }

        public void setTop(int top) {
            this.top = top;
        }

        public int getBottom() {
            return bottom;
        }

        public void setBottom(int bottom) {
            this.bottom = bottom;
        }
    }
动态填充数据实现
 public void initData(List<String> list) {
        ViewGroup.MarginLayoutParams pa = new ViewGroup.MarginLayoutParams(ViewGroup.MarginLayoutParams.WRAP_CONTENT,
                ViewGroup.MarginLayoutParams.WRAP_CONTENT);
        int size = list.size();
        for (int i = 0; i < size; i++) {
            TextView tv = new TextView(getContext());
            tv.setText(list.get(i));
            addView(tv, pa);
            ((ViewGroup.MarginLayoutParams) tv.getLayoutParams()).setMargins(DensityUtils.dp2px(getContext(), 5), DensityUtils.dp2px(getContext(), 5),
                    DensityUtils.dp2px(getContext(), 5), DensityUtils.dp2px(getContext(), 5));
            tv.setBackgroundResource(R.drawable.flag_01);
        }
    }

添加点击事件

public interface IOnTabClickListener {
        void onTabClick(int position, TextView textView);
    }

private void setOnclick(final int position, final TextView textView) {
        textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                iOnTabClickListener.onTabClick(position, textView);
            }
        });
    }
后记

比较难理解的部分应该就是onMeasure了。。当设置wrap的时候找到宽度最大的值。。并且设置每个view的坐标.

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

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 172,110评论 25 707
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,429评论 2 45
  • 阿狸,我最爱的东西!很有心的他给我买了好多关于阿狸的东西,漫画书,涂鸦本,玩偶,都是阿狸!可能在他的心里,我...
    全世界我想遇见你阅读 265评论 0 0
  • 很认真的想写点什么,却思绪万千。 似乎千军万马奔过心头, 仿佛百丈冰原突然倒塌, 好像宇宙黑洞离奇吸引。 人的内心...
    知鱼之乐V阅读 2,536评论 2 2
  • 2017.8.31 八月的最后一天 好的坏的就都留在八月吧 听着七尾旅人的【八月】 抬头眯着眼透过树叶看阳光 低头...
    哄小轰阅读 258评论 1 3