AndroidUI系列-ViewGroup流式布局

很多时候,我们会遇见各种各样的需求,流式布局算是非常常见的一种。像各种菜单啊,展示之类的。其实这个很简单,可以自己手写一个,顺便练练自定义控件。先看看效果。

这里写图片描述

那么先来分析一下,满足这个需求,应该需要做哪些准备。

这里写图片描述

就像备注写的一样,
首先需要准备的条件:
一个List<List< View > > 来缓存多少行。
一个List<Integer> 来缓存每一行的高度。
一个List<View> 来缓存每一行的子控件View。
相对于每一行来说,需要一个变量缓存当前行的宽度,一个变量缓存当前行的最大高度。

换行的条件:
当前行的宽度加上下一个子控件的宽度,超过了当前控件允许的最大宽度。那就换行。

那么直接开始撸吧。

package com.example.administrator.flowlayout;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;

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

/**
 * Created by ShuWen on 2017/6/1.
 */

public class FlowLayout extends ViewGroup {

    //用于缓存的多少行
    private List<List<View>> mLineViewsList = new ArrayList<>();
    //用于缓存每一行最大的高度
    private List<Integer> mLinesHieights = new ArrayList<>();

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

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

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

    //为了获取子控件的margin属性值
    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(),attrs);
    }

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

        //获取测量模式
        int meaWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        int meaHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        //获得允许的宽高
        int meaWidthSize = MeasureSpec.getSize(widthMeasureSpec);
        int meaHeightSize = MeasureSpec.getSize(heightMeasureSpec);
        //最后测量的宽高
        int measuredWidth = 0;
        int measuredHeight = 0;

        if (meaHeightMode == MeasureSpec.EXACTLY && meaWidthMode == MeasureSpec.EXACTLY){
            measuredHeight = meaHeightSize;
            measuredWidth = meaWidthSize;
        }else {
            int iCurLineW = 0;
            int iCurLineH = 0;
            int childWidth = 0;
            int childHeight = 0;
            int childCount = getChildCount();
            //用于缓存每一行的子控件
            List<View> childsList = new ArrayList<>();

            for (int i = 0; i < childCount; i++) {
                View childView = getChildAt(i);
                //测量子控件,获得子控件的宽高和margin值
                measureChild(childView,widthMeasureSpec,heightMeasureSpec);
                MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();
                //自控件的宽高
                childWidth = params.leftMargin + childView.getMeasuredWidth() + params.rightMargin;
                childHeight = params.topMargin + childView.getMeasuredHeight() + params.bottomMargin;
                //当前行的宽度,加上下一个控件的宽度大于允许值,则换行
                if (childWidth + iCurLineW > meaWidthSize){
                    //换行操作,记录测量的父控件宽高
                    measuredWidth = Math.max(measuredWidth,iCurLineW);
                    measuredHeight += iCurLineH;
                    //保存该行的数据
                    mLineViewsList.add(childsList);
                    mLinesHieights.add(iCurLineH);
                    //重新记录新的一行
                    iCurLineH = childHeight;
                    iCurLineW = childWidth;
                    //开始缓存新一行数据
                    childsList = new ArrayList<>();
                    childsList.add(childView);

                }else {
                    //未换行操作,记录该行宽高
                    iCurLineH = Math.max(iCurLineH,childHeight);
                    iCurLineW += childWidth;
                    //保存到该行集合
                    childsList.add(childView);
                }

                //当该行是最后一行并且需要换行时,进行换行数据处理
                if (i == childCount - 1){

                    measuredHeight += iCurLineH;
                    measuredWidth = Math.max(measuredWidth,iCurLineW);

                    mLinesHieights.add(iCurLineH);
                    mLineViewsList.add(childsList);
                }

            }
        }

        setMeasuredDimension(measuredWidth,measuredHeight);

    }

    @Override
    protected void onLayout(boolean b, int i, int i1, int i2, int i3) {
        int left,top,right,bottom;
        int curLeft = 0;
        int curTop = 0;
        int linesCount = mLineViewsList.size();

        for (int j = 0; j < linesCount; j++) {
            List<View> childViews = mLineViewsList.get(j);
            int childsCount = childViews.size();

            for (int k = 0; k < childsCount; k++) {
                View childView = childViews.get(k);
                MarginLayoutParams params = (MarginLayoutParams) childView.getLayoutParams();
                left = curLeft + params.leftMargin;
                top = curTop + params.topMargin;
                right = left + childView.getMeasuredWidth();
                bottom = top + childView.getMeasuredHeight();
                //为子控件布局
                childView.layout(left,top,right,bottom);
                curLeft += params.leftMargin + childView.getMeasuredWidth() + params.rightMargin;
            }

            curLeft = 0;
            curTop += mLinesHieights.get(j);
        }
        mLinesHieights.clear();
        mLineViewsList.clear();
    }

    public interface onItemClick{
        void click(View view,int position);
    }

    public void setOnItemClickListener(final onItemClick onItemClick){
        int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            final int finalI = i;
            childView.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View view) {
                    onItemClick.click(view, finalI);
                }
            });
        }
    }
}

其中用到的flag背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <corners android:radius="10dp"/>
    <padding android:bottom="2dp"
        android:top="2dp"
        android:right="10dp"
        android:left="10dp"/>
    <solid android:color="@color/colorPrimary"/>
</shape>

textView的样式.

<style name="text_flag">
        <item name="android:background">@drawable/flag</item>
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:layout_margin">4dp</item>
        <item name="android:textColor">#fff</item>
    </style>

activity的布局:

<?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:id="@+id/activity_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.flowlayout.MainActivity">

    <com.example.administrator.flowlayout.FlowLayout
        android:id="@+id/flowlayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            style="@style/text_flag"
            android:text="阿萨德 "/>
        <TextView
            style="@style/text_flag"
            android:text="我阿萨德阿萨德的"/>
        <TextView
            style="@style/text_flag"
            android:textSize="16sp"
            android:text="你阿萨德阿萨德的"/>
        <TextView
            style="@style/text_flag"
            android:textSize="19sp"
            android:text="阿萨德 阿萨德"/>
        <TextView
            style="@style/text_flag"
            android:text="阿萨德阿萨德"/>
        <TextView
            style="@style/text_flag"
            android:text="阿大声道"/>
        <TextView
            style="@style/text_flag"
            android:text="阿大声道"/>
        <TextView
            style="@style/text_flag"
            android:text="为全文完请二位"/>
        <TextView
            style="@style/text_flag"
            android:text="谁是谁"/>
        <TextView
            style="@style/text_flag"
            android:text="撒大声地"/>
        <TextView
            style="@style/text_flag"
            android:text="阿大声道"/>
        <TextView
            style="@style/text_flag"
            android:text="大法师"/>
        <TextView
            style="@style/text_flag"
            android:text="12123"/>
        <TextView
            style="@style/text_flag"
            android:text="sadsa"/>
    </com.example.administrator.flowlayout.FlowLayout>
</LinearLayout>

就这么简单,自己撸一遍吧,总能学到一点的。

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

推荐阅读更多精彩内容