The onMeasure method is where a custom layout calculates how big it and its children want to be. This helps the system allocate space properly.
The onLayout method is responsible for placing each child view at the correct position and size inside the parent ViewGroup.
onMeasure method, what will be the measured width and height of the ViewGroup?
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val widthSize = MeasureSpec.getSize(widthMeasureSpec)
val heightSize = MeasureSpec.getSize(heightMeasureSpec)
setMeasuredDimension(widthSize / 2, heightSize / 2)
}The code sets the measured dimensions to half the available width and height, so the ViewGroup will be smaller than the space given.
onLayout method but the children are not visible:
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
// No calls to child.layout()
}
Why are the children not visible?Without calling child.layout() for each child, the system doesn't know where to place them, so they don't appear.
onMeasure and onLayout to correctly size and position children?Padding reduces the space available for children, so it must be subtracted from the size during measurement and used as an offset when positioning children.
