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)
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值