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 中国大陆许可协议进行许可。

posted @   ou尼酱~~~  阅读(94)  评论(1编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起