1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| class FlowLayout @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null ) : ViewGroup(context, attrs) { var horizontalSpacing = 16.dp.toPx().toInt() var verticalSpacing = 16.dp.toPx().toInt() override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val width = MeasureSpec.getSize(widthMeasureSpec) var lineHeight = 0 var x = paddingLeft var y = paddingTop var maxHeight = 0 for (i in 0 until childCount) { val child = getChildAt(i) measureChild(child, widthMeasureSpec, heightMeasureSpec) if (x + child.measuredWidth > width - paddingRight) { x = paddingLeft y += lineHeight + verticalSpacing lineHeight = 0 } x += child.measuredWidth + horizontalSpacing lineHeight = maxOf(lineHeight, child.measuredHeight) maxHeight = y + lineHeight } maxHeight += paddingBottom setMeasuredDimension(width, resolveSize(maxHeight, heightMeasureSpec)) } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { var x = paddingLeft var y = paddingTop var lineHeight = 0 for (i in 0 until childCount) { val child = getChildAt(i) if (x + child.measuredWidth > r - l - paddingRight) { x = paddingLeft y += lineHeight + verticalSpacing lineHeight = 0 } child.layout(x, y, x + child.measuredWidth, y + child.measuredHeight) x += child.measuredWidth + horizontalSpacing lineHeight = maxOf(lineHeight, child.measuredHeight) } } }
|