view 自定义 layout模板
class TagLayout(context: Context?, attrs: AttributeSet?) : ViewGroup(context, attrs) { private val childrenBounds = mutableListOf<Rect>()//用于存储摆放子view的数据 override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { var widthUsed = 0 var heightUsed = 0 var lineWidthUsed = 0 var lineMaxHeight = 0 val specWidthSize = MeasureSpec.getSize(widthMeasureSpec) val specWidthMode = MeasureSpec.getMode(widthMeasureSpec) for ((index, child) in children.withIndex()) { measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, heightUsed)//测量子view,不需要手动一大堆模式判断了 if (specWidthMode != MeasureSpec.UNSPECIFIED && lineWidthUsed + child.measuredWidth > specWidthSize) {//测量之后就可以使用view的measuredWidth、measuredHeight属性了 lineWidthUsed = 0 heightUsed += lineMaxHeight lineMaxHeight = 0 measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, heightUsed)//不对劲再测量一次 } if (index >= childrenBounds.size) { childrenBounds.add(Rect()) } val childBounds = childrenBounds[index] childBounds.set(lineWidthUsed, heightUsed, lineWidthUsed + child.measuredWidth, heightUsed + child.measuredHeight)//每个子view测量之后得到的数据记得存储 lineWidthUsed += child.measuredWidth widthUsed = max(widthUsed, lineWidthUsed) lineMaxHeight = max(lineMaxHeight, child.measuredHeight) } val selfWidth = widthUsed val selfHeight = heightUsed + lineMaxHeight setMeasuredDimension(selfWidth, selfHeight)//最后view group总的宽度、高度,设置一波!! } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {//模板写!!只要按照列表里的数据摆放就行了!! for ((index, child) in children.withIndex()) { val childBounds = childrenBounds[index] child.layout(childBounds.left, childBounds.top, childBounds.right, childBounds.bottom)//view group的onLayout记得调用view的layout } } override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {//一定要加,不然measure child时发生转型错误 return MarginLayoutParams(context, attrs) } }
本文作者:ou尼酱~~~
本文链接:https://www.cnblogs.com/--here--gold--you--want/p/15684028.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步