[自定义view]FlowLayout简单实现

89 阅读1分钟
class FlowHorizontalLayout @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet,
    defStyle: Int = 0,
) : FrameLayout(context,attributeSet,defStyle) {

    var mLeft = 0 //定义每次布局view的left位置
    var mTop = 0 //定义每次布局view的top位置

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        //1、遍历FlowHorizontalLayout的子view
        children.forEach { 
        //2、拿到子view的尺寸用于布局
            val h = it.measuredHeight
            val w = it.measuredWidth

        //3、如果这行放不下,换一行
            if(mLeft + w > width){
                mLeft = 0 //重置mLeft
                mTop += h //更新mTop
            }
         //4、把view布局出来
            it.layout(mLeft,mTop,mLeft+w,mTop+h)
         //5、该view布局完后,更新mLeft(也就是新的view放在旧的view的后面)
            mLeft += w 
        }
    }
}