Complete the code to create a custom View class named MyView.
class MyView(context: Context) : View([1]) { }
The custom View class constructor must pass the context parameter to the superclass View.
Complete the code to override the onMeasure method and set the view size.
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
setMeasuredDimension([1], height)
}Use the calculated width value to set the measured width dimension.
Fix the error in the onDraw method to draw a red circle.
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val paint = Paint()
paint.color = [1]
canvas.drawCircle(width / 2f, height / 2f, 100f, paint)
}To draw a red circle, set the paint color to Color.RED.
Fill both blanks to create a custom layout that measures children with exact width and height.
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val width = MeasureSpec.getSize(widthMeasureSpec)
val height = MeasureSpec.getSize(heightMeasureSpec)
val childWidthSpec = MeasureSpec.makeMeasureSpec(width, [1])
val childHeightSpec = MeasureSpec.makeMeasureSpec(height, [2])
for (i in 0 until childCount) {
getChildAt(i).measure(childWidthSpec, childHeightSpec)
}
setMeasuredDimension(width, height)
}Use MeasureSpec.EXACTLY to tell children to measure with exact size.
Fill all three blanks to create a custom layout that positions children vertically stacked.
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
var currentTop = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
val childHeight = child.measuredHeight
child.layout(l, currentTop, r, currentTop + [1])
currentTop += [2] + [3]
}
}The child is laid out from currentTop to currentTop + childHeight. Then currentTop moves down by childHeight plus 10 pixels spacing.