Custom layout manager

A ViewGroup is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers.

To create own views container or layout manager you can modify existing classes like FrameLayout.

The ViewGroup.LayoutParams class allows view to tell their parents how they want to be laid out. Typically, layout managers have their own implementation of this class.

Layout manager template

Override the onMeasure() method to calculate sizes of children using measureChild() or measureChildWithMargins() method.

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
    var i = 0
    val count: Int = getChildCount()

    while (i < count) {
        val child: View = getChildAt(i)
        if (child.getVisibility() !== GONE) {
            measureChild(child, widthMeasureSpec, heightMeasureSpec)
        }
        i++
     }
    
    // !!! must be called
    setMeasuredDimension(      
        MeasureSpec.getSize(widthMeasureSpec),
        MeasureSpec.getSize(heightMeasureSpec))
}

Override the onLayout method to set positions of children. This method is called after onMeasure(). Task will be completed when layout() method is called once for all children.

override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
    var i = 0
    val count: Int = getChildCount()
    while (i < count) {
        val child: View = getChildAt(i)
        if (child.getVisibility() !== GONE) {
            child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight())
        }
        i++
    }
}

You can add own layout attributes (read more in custom view )

<declare-styleable name="CustomLayoutLP">
    <attr name="android:layout_gravity" />
    <attr name="layout_position">
        <enum name="middle" value="0" />
        <enum name="left" value="1" />
        <enum name="right" value="2" />
    </attr>
</declare-styleable>
Simple Custom layout example