0

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)
    }
}
kewCogs
  • 21
  • 3

1 Answers1

0

OK, I found the answer I was looking for.

I needed to implement onMeasure, as detailed in this answer to another question. Pay particular attention to the case where the MeasureSpec mode is set to MeasureSpec.AT_MOST as this is the mode used when wrap_content is specified. Since Android Studio layout editor sets wrap_content for both dimensions by default, the view will have this size when dragged from the palette.

kewCogs
  • 21
  • 3