Android 自定义ViewGroup (FlowLayout:流式布局)

image.png

引言

Android 系统为我们提供了各种各样的常见控件来满足我们的日常需求,但是谁能不爱美呢.常见的系统控件满足了我们的功能需要,但是原生控件确实不好看这个时候就需要我们做改造了 或者更改Style 或者改颜色背景.但是一些需求原生控件满足不了日益强大的UI的时候我们只能自定义View来实现,比如说各种奇形怪状的控件,各种奇怪的进度条...这个时候我们就需要自己写了.一切从爹开始,继承爹的财产好干事儿,我们继承View这个爹 然后自定义我们的控件就行了

背景介绍

日常需求中我们会遇到各种标签单个或者多个展示的情况,单个标签直接做个TextView+Shape搞定,多个的时候需要处理自动换行的逻辑了.最近准备换工作,想到了这几年做的一些东西特此总结一下,方便回头cv,这里不做选中状态以及编辑的逻辑(个人感觉,提供基础的展示更方便扩展).

功能

  • Labels背景的角度
  • Labels内容的padding
  • Labels 的边距Margin
  • Labels 的背景色
  • Labels 的点击事件

插入知识点:自定义属性
Android 自定义属性

1.attrs.xml自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <declare-styleable name="FlowLayoutStyle">
        <!--        Labels的文字-->
        <attr name="flTextColor" format="color" />
        <!--        Labels的背景色-->
        <attr name="flBackgroundColor" format="color" />
        <!--        Labels的角度大小-->
        <attr name="flAngleSize" format="float" />
        <!--        Labels的左右 Margin-->
        <attr name="flMarginLeftAndRight" format="integer" />
        <!--        Labels的上下 Margin-->
        <attr name="flMarginTopAndBottom" format="integer" />
        <!--      Labels 内容上下padding  -->
        <attr name="flPaddingTopAndBottom" format="integer" />
        <!--      Labels 内容左右padding  -->
        <attr name="flPaddingLeftAndRight" format="integer" />
    </declare-styleable>

</resources>

2.xml引用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

   <com.wkq.flow.FlowLayout
       android:background="@color/teal_200"
       android:id="@+id/fl"
       android:layout_width="wrap_content"
       app:flBackgroundColor="@color/purple_200"
       app:flTextColor="@color/white"
       app:flAngleSize="10"
       app:flPaddingLeftAndRight="40"
       app:flPaddingTopAndBottom="10"
       app:flMarginLeftAndRight="40"
       app:flMarginTopAndBottom="30"
       android:layout_height="wrap_content"/>

</RelativeLayout>

3.FlowLayout实现

package com.wkq.flow

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.text.TextUtils
import android.util.AttributeSet
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TextView
import com.wkq.flow.util.PixelsUtil


/**
 * @author wkq
 *
 * @date 2022年07月08日 10:12
 *
 *@des
 *
 */

class FlowLayout @JvmOverloads constructor(
        context: Context,
        attrs: AttributeSet? = null,
        defStyleAttr: Int? = 0
) :
        ViewGroup(context, attrs, defStyleAttr!!, 0) {

    //背景颜色
    var bgcolor: Int = 0

    //文字颜色
    var textColor: Int = 0

    //padding
    var mLeftAndRightPadding = 10
    var mTopAndBottomPadding = 5

    //边距
    var leftAndRightMargin = 1
    var topAndBottomMargin = 1
    //角度
    var flAngleSize = 1f
    //点击监听
    var listener: FlowLayoutLabelslListener? = null

    //内容集合
    var textList = ArrayList<String>()

    init {
        var style = context.obtainStyledAttributes(attrs, R.styleable.FlowLayoutStyle)
        bgcolor = style.getColor(  R.styleable.FlowLayoutStyle_flBackgroundColor,context.resources.getColor(R.color.bg_color))
        textColor = style.getColor( R.styleable.FlowLayoutStyle_flTextColor,  context.resources.getColor(R.color.text_color) )
        mLeftAndRightPadding = style.getInt(R.styleable.FlowLayoutStyle_flPaddingLeftAndRight, 10)
        mTopAndBottomPadding = style.getInt(R.styleable.FlowLayoutStyle_flPaddingTopAndBottom, 5)
        leftAndRightMargin = style.getInt(R.styleable.FlowLayoutStyle_flMarginLeftAndRight, 10)
        topAndBottomMargin = style.getInt(R.styleable.FlowLayoutStyle_flMarginTopAndBottom, 5)
        flAngleSize = style.getFloat(R.styleable.FlowLayoutStyle_flAngleSize, 10f)
    }

    /**
     * 设置点击监听
     */
    fun addLabelsListener(listener: FlowLayoutLabelslListener) {
        this.listener = listener
    }

    override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams? {
        return MarginLayoutParams(context, attrs)
    }

    //宽度
    var lineHight = 0
    var mRealWidth = 0
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        measureChildren(widthMeasureSpec, heightMeasureSpec);
        //获取测量模式
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)
        var heightSize = MeasureSpec.getSize(heightMeasureSpec)
        // kotlin for循环中 .. 包含最后一个数  until  不包含最后一次
        var groupHeight = 0
        var maxWidth = 0
        var curWidth = 0;
        groupHeight = getChildAt(0).measuredHeight + topAndBottomMargin
        for (index in 0 until childCount) {
            val currentView = getChildAt(index);
            //测量后才能获取宽高
            lineHight = (currentView.measuredHeight + topAndBottomMargin)
            var viewWidth = (currentView.measuredWidth + leftAndRightMargin)
            if ((viewWidth + curWidth) > (widthSize - leftAndRightMargin)) {
                // 一行不满足需要换行
                groupHeight += lineHight
                curWidth = 0
            } else {
                curWidth += (viewWidth)
            }
            maxWidth = Math.max(maxWidth, curWidth)
        }
        groupHeight = Math.max(groupHeight, lineHight)

        //作为一个ViewGroup,它自己也是一个View,它的大小也要根据它的父View给他提供的宽高来度量
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        val heigthMode = MeasureSpec.getMode(heightMeasureSpec)
        //如果是实际大小,则直接使用设置的具体值
        val realWidth = if (widthMode == MeasureSpec.EXACTLY) widthSize else (maxWidth + leftAndRightMargin)
        val realHeight = if (heigthMode == MeasureSpec.EXACTLY) heightSize else (groupHeight + topAndBottomMargin)
        //保存测量的大小
        setMeasuredDimension(realWidth, realHeight)
        mRealWidth = realWidth
    }

    var linNum = 1
    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        // 布局的位置
        var left: Int = 0
        var top: Int = 0
        var right: Int = 0
        var bottom: Int = 0

        var curLeft = 0
        var curTop = 0
        for (index in 0 until childCount) {
            var view = getChildAt(index)
            //一行的高度
            lineHight = view.measuredHeight + topAndBottomMargin

            if ((right + view.measuredWidth) > mRealWidth) {
                //需要换行
                linNum += 1
                left = leftAndRightMargin
                top = lineHight * (linNum - 1) + topAndBottomMargin
                right = left + view.measuredWidth
                bottom = top + view.measuredHeight
                view.layout(left, top, right, bottom)
                curLeft = right
            } else {
                left = leftAndRightMargin + curLeft
                top = (linNum - 1) * view.measuredHeight + linNum * topAndBottomMargin
                right = left + view.measuredWidth
                bottom = top + view.measuredHeight
                view.layout(left, top, right, bottom)
                curLeft = right
            }

        }


    }

    /**
     * 设置标签数据
     */
    fun addLabels(labels: ArrayList<String>, isAdd: Boolean = true) {
        if (labels == null || labels.size == 0) return
        if (isAdd) {
            textList.addAll(labels)
        } else {
            textList = labels
        }
        textList.forEach {
            if (it != null && !TextUtils.isEmpty(it.toString()))
                addTextView(it)
        }
    }

    /**
     * 添加单个标签
     */
    fun addLabels(textContent: String, isAdd: Boolean = true) {
        if (textContent != null && TextUtils.isEmpty(textContent.toString())) return
        if (isAdd) {
            textList.add(textContent)
        } else {
            textList.clear()
            textList.add(textContent)
        }

        addTextView(textContent)

    }

    private fun addTextView(textContent: String) {
        var textDrawable = GradientDrawable()
        textDrawable.setColor(bgcolor)
        textDrawable.cornerRadius = flAngleSize
        var textView = TextView(context)
        textView.text = textContent
        textView.setBackground(textDrawable)
        textView.setTextColor(textColor)
        textView.setGravity(Gravity.CENTER);
        textView.setPadding(mLeftAndRightPadding, mTopAndBottomPadding, mLeftAndRightPadding, mTopAndBottomPadding)
        textView.setOnClickListener {
            if (listener != null) listener!!.onLabelsClick(textContent)
        }
        addView(textView)
    }

    interface FlowLayoutLabelslListener {

        fun onLabelsClick(content: Any);

    }
}

总结
FlowLayout实现流式布局,这里只提供了角度,背景颜色,边距,padding,点击事件等基础功能.后期可以在此基础上根据业务需要扩展选中,编辑等功能

欢迎点赞!!!

源码

源码地址

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