读源码,懂原理,有何用?写业务代码又用不到?—— 自定义换行容器控件

回想一下在做文本上写做的场景,当从左到右写满一行后,会切换到下一行的开头继续写。若是把“做文本”比做容器控件,把“字”比做子控件。Android 原生控件中没有能“自动换行”的容器控件,若不断向LinearLayout中添加View,它们会沿着一个方向不断堆叠,即便实际绘制位置已经超出屏幕。git

在 GitHub 上找到了一些实现自动换行功能的容器控件,但使用过程当中发现略“重”,并且大部分都把“子控件选中状态”和“自动换行”耦合在一块儿。使得切换选中方式变得困难。“多控件间的选中模式”和“自动换行的容器控件”是两个相互独立的概念,分开实现这两个功能会使得代码能够更加灵活地组合。“多控件间的选中模式”在以前的不再要和产品经理吵架了——Android自定义控件之单选按钮中有详细的介绍。github

本文试着从零开始手写一个带自动换行功能的容器控件。算法

这是 Android 视图绘制系列文章的第三篇,系列文章目录以下:bash

  1. View绘制原理——画多大?
  2. View绘制原理——画在哪?
  3. View绘制原理——画什么?
  4. 读源码,懂原理,有什么用?写业务代码又用不到?—— 自定义换行容器控件

业务场景

自动换行容器控件的典型应用场景是:“动态多选按钮”,即多选按钮的个数和内容是动态变化的,这样就不能把它们写死在布局文件中,而须要动态地调用addView()添加到容器控件中。 效果以下:app

自动换行容器控件

点击一下 button 就会调用addView()向容器控件中添加一个 TextView 。dom

背景知识

若是了解“View绘制原理”中的测量和布局的过程,就能垂手可得地自定义自动换行容器控件。这两个过程的详细介绍能够分别点击View绘制原理——画多大?View绘制原理——画在哪?ide

简单回顾一下这一系列文章的结论:布局

  • View 绘制包含三个步骤,依次是测量、布局、绘制。它们分别解决了三个问题:画多大?,画在哪?,画什么?post

  • “画多大?”是为了计算出控件自己的宽高占用多少像素。对于容器控件来讲就是“以不一样方式排列的子控件的总宽高是多少像素。”学习

  • “画在哪?”是为了计算出控件相对于屏幕左上角的相对位置。对于容器控件来讲就是“如何安排每一个子控件相对于本身左上角的相对位置”。(当每一个控件相对于父控件都有肯定的位置时,只要遍历完 View 树,屏幕上全部控件的具体位置都得以肯定)

  • 容器控件用于组织若干子控件,因此它的主要工做是敦促全部子控件测量并布局本身,它本身并不须要绘制图案,因此自定义容器控件时不须要关心“画什么?”

重写 onMeasure()

通过上面的分析,自定义自动换行容器控件只须要继承ViewGroup并重写onMeasure()onLayout()

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

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {}

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {}
}
复制代码

本文将使用 Kotlin 做为开发语音,Kotlin 可读性超高,相信即便没有学习过它也能看懂。关于 Kotlin 的语法细节和各类实战能够点击这里

对于容器控件来讲,onMeasure()须要作两件事情:

  1. 敦促全部子控件本身测量本身以肯定自身尺寸 。
  2. 计算出容器控件的尺寸。

好在ViewGroup中提供了一个方法来帮助咱们完成全部子控件的测量:

public abstract class ViewGroup extends View {

    protected void measureChildren(int widthMeasureSpec, int heightMeasureSpec) {
        final int size = mChildrenCount;
        final View[] children = mChildren;
        //'遍历全部子控件并触发它们本身测量本身'
        for (int i = 0; i < size; ++i) {
            final View child = children[i];
            if ((child.mViewFlags & VISIBILITY_MASK) != GONE) {
                measureChild(child, widthMeasureSpec, heightMeasureSpec);
            }
        }
    }
        
    protected void measureChild(View child, int parentWidthMeasureSpec, int parentHeightMeasureSpec) {
        final LayoutParams lp = child.getLayoutParams();
        final int childWidthMeasureSpec = getChildMeasureSpec(parentWidthMeasureSpec, mPaddingLeft + mPaddingRight, lp.width);
        final int childHeightMeasureSpec = getChildMeasureSpec(parentHeightMeasureSpec, mPaddingTop + mPaddingBottom, lp.height);
        //'将父控件的约束和子控件的诉求相结合造成宽高两个MeasureSpec,并传递给孩子以指导它测量本身'
        child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
    }
}
复制代码

只有当全部子控件尺寸都肯定了,才能知道父控件的尺寸,就比如只有知道了全班每一个人的体重,才能知道全班的整体重。因此onMeasure()中应该首先调用measureChildren()

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

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        measureChildren(widthMeasureSpec, heightMeasureSpec)
    }

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {}
}
复制代码

自动换行的容器控件的宽度应该是手动指定的(没有固定宽度何来换行?)。而高度应该将全部控件高度相累加。因此在onMeasure()中需遍历全部的孩子并累加他们的高度:

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

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        measureChildren(widthMeasureSpec, heightMeasureSpec)
        //'获取容器控件的宽度(即布局文件中指定的宽度)'
        val width = MeasureSpec.getSize(widthMeasureSpec)
        //'定义容器控件的初始高度为0'
        var height = 0
        //'容器控件当前行剩下的空间'
        var remainWidth = width
        //'遍历全部子控件并用自动换行的方式累加其高度'
        (0 until childCount).map { getChildAt(it) }.forEach { child ->
            val lp = child.layoutParams as LinearLayout.LayoutParams
            //'当前行已满,在新的一行放置子控件'
            if (isNewLine(lp, child, remainWidth)) {
                remainWidth = width - child.measuredWidth
                //'容器控件新增一行的高度'
                height += (lp.topMargin + lp.bottomMargin + child.measuredHeight)
            } 
            //'当前行未满,在当前行右侧放置子控件'
            else {
                //'消耗当前行剩余宽度'
                remainWidth -= child.measuredWidth
                if (height == 0) height = (lp.topMargin + lp.bottomMargin + child.measuredHeight)
            }
            //将子控件的左右边距也考虑在内
            remainWidth -= (lp.leftMargin + lp.rightMargin)
        }
        //'控件测量的终点,即容器控件的宽高已肯定'
        setMeasuredDimension(width, height)
    }

    //'判断是否须要新起一行:若是子控件宽度加上左右边距大于当前行剩余宽度,则需新起一行'
    private fun isNewLine(lp: LinearLayout.LayoutParams, child: View, remainWidth: Int) = lp.leftMargin + child.measuredWidth + lp.rightMargin > remainWidt
}
复制代码

整个测量算法的目的是肯定容器控件的宽度和高度,关键是要维护好当前行剩余空间remainWidth的值。测量过程的终点是View.setMeasuredDimension()的调用,它表示着容器控件尺寸已经有肯定值。

重写 onLayout()

在肯定了容器控件及其全部子控件的尺寸后,下一步就是肯定全部子控件的位置:

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

    override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
        //'当前横坐标(相对于容器控件左边界的距离)'
        var left = 0
        //'当前纵坐标(相对于容器控件上边界的距离)'
        var top = 0
        //'上一行底部的纵坐标(相对于容器控件上边界的距离)'
        var lastBottom = 0
        //'遍历全部子控件以肯定它们相对于容器控件的位置'
        (0 until childCount).map { getChildAt(it) }.forEach { child ->
            val lp = child.layoutParams as LinearLayout.LayoutParams
            //'新起一行'
            if (isNewLine(lp, child, r - l - left)) {
                left = -lp.leftMargin
                //'更新当前纵坐标'
                top = lastBottom
                //'上一行底部纵坐标置0,表示须要从新被赋值'
                lastBottom = 0
            }
            //'子控件左边界'
            val childLeft = left + lp.leftMargin
            //'子控件上边界'
            val childTop = top + lp.topMargin
            //'肯定子控件上下左右边界相对于父控件左上角的距离'
            child.layout(childLeft, childTop, childLeft + child.measuredWidth, childTop + child.measuredHeight)
            //'更新上一行底部纵坐标'
            if (lastBottom == 0) lastBottom = child.bottom + lp.bottomMargin
            left += child.measuredWidth + lp.leftMargin + lp.rightMargin
        }
    }

    //'判断当前子控件是否应该放置在新一行'
    private fun isNewLine(left: Int, lp: LinearLayout.LayoutParams, child: View, parentWidth: Int) = 
        left + lp.leftMargin + child.measuredWidth + lp.rightMargin > parentWidth

}
复制代码

子控件的位置使用它上下左右四个点相对于父控件左上角的距离来描述。因此肯定全部子控件位置的算法关键是维护好当前插入位置的横纵坐标,每一个子控件的位置都是在当前插入位置上加上本身的宽高来肯定的。

容器控件调用child.layout()触发子控件定位本身,子控件最终会调用setFrame()以最终肯定本身相对于父控件的位置。

public class View {
    public void layout(int l, int t, int r, int b) {
        ...
        //'调用setFrame()'
        boolean changed = isLayoutModeOptical(mParent) ?setOpticalFrame(l, t, r, b) : setFrame(l, t, r, b);
        ...
    }
    
    protected boolean setFrame(int left, int top, int right, int bottom) {
            ...
            //'为上下左右赋值'
            mLeft = left;
            mTop = top;
            mRight = right;
            mBottom = bottom;
            ...
    }
}
复制代码

如今就能够像这样来使用LineFeedLayout了:

class MainActivity : AppCompatActivity() {
    private var index = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        //'当点击按钮是动态添加TextView到自动换行容器控件中'
        btnAdd.setOnClickListener {
            //'构建TextView'
            TextView(this).apply {
                text = ”Tag ${index}“
                textSize = 20f
                setBackgroundColor(Color.parseColor(”#888888“))
                gravity = Gravity.CENTER
                setPadding(8, 3, 8, 3)
                setTextColor(Color.parseColor(”#FFFFFF“))
                layoutParams = LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
                ).apply {
                    rightMargin = 15
                    bottomMargin = 40
                }
            //'将TextView动态添加到容器控件container中'
            }.also { container?.addView(it) }
            index++
        }
    }
}
复制代码

若是但愿子控件之间存在多选、单选、菜单选,这类互斥选中关系,能够将 demo 中的 TextView 替换成 自定义控件Selector,关于该控件的介绍详见不再要和产品经理吵架了——Android自定义控件之单选按钮

Talk is cheap, show me the code

完整代码能够点击这里

相关文章
相关标签/搜索