I would like to control how my custom views are initially sized and displayed when using Design mode in Android Studio's layout editor.
For example, the trivial view below (copied from a tutorial blog), when added to a ConstraintLayout, defaults to a layout_width
and layout_height
of wrap_content
. It displays in the preview as filling the parent view. This can make it difficult to manipulate the layout 'blobs' to achieve the desired layout.
Worse, when I drag from the palette directly to the design surface, the view is given x and y offsets which place the bottom and right hand 'blobs' off the design surface altogether. detail from layout editor
It would be very useful if I were able to give my custom views sensible defaults, much in the way that a regular Button view is.
class MyView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val myPaint = Paint().apply {
style = Paint.Style.STROKE
color = Color.RED
strokeWidth = 30f
}
override fun onDraw(canvas: Canvas) {
val left = paddingLeft.toFloat()
val top = paddingTop.toFloat()
val right = width.toFloat() - paddingRight
val bottom = height.toFloat() - paddingBottom
canvas.drawLine(left, bottom, right, top, myPaint)
}
}