view 自定义 layout模板


class TagLayout(context: Context?, attrs: AttributeSet?) : ViewGroup(context, attrs) {
  private val childrenBounds = mutableListOf()//用于存储摆放子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)
  }
}

相关