android 创建简单的FlowLayout布局

本文介绍了在Android中通过继承ViewGroup自定义SimpleFlowLayout布局的核心实现,重点涵盖onMeasure和onLayout方法的重写逻辑:遍历子View进行测量,并按行依次水平摆放子View,支持基本流式布局功能。代码使用Kotlin编写,适用于需要动态换行显示子控件的场景。

点击查看代码
package com.run.treadmill
import android.content.Context
import android.util.AttributeSet
import android.view.ViewGroup
class SimpleFlowLayout:ViewGroup {
    constructor(context: Context) : super(context){
        init(null)
    }
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs){
    }
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context,
        attrs,
        defStyleAttr){
    }
    private fun init(attrs: AttributeSet?){}
    //1.测量控件大小
    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        //测量所有的子View
        for (i in 0 until childCount){
            val child=getChildAt(i)
            measureChild(child,widthMeasureSpec,heightMeasureSpec)
        }
    }

    override fun onLayout(
        p0: Boolean,
        p1: Int,
        p2: Int,
        p3: Int,
        p4: Int
    ) {
        var left=0
        var top=0
        //摆放子view
        for (i in 0 until childCount){
            val child=getChildAt(i)
            child.layout(left,top,left+child.measuredWidth,top+child.measuredHeight)
            left+=child.measuredWidth
        }
    }
}
posted @ 2026-10-21 11:18  xiao250  阅读(2)  评论(0)    收藏  举报