I am attempting to experiment in creating my own Views by subclassing “View.” I want to simulate a new Button type class that will be drawn with the onDraw where I simply draw a rectangle from the canvas being passed in. I then add that custom View into the layout XML file, but I cannot control its size. For example, I set the width to “fill_parent” and the height to “wrap_content” but I don’t know what the content of my View is. (BTW, the LinearLayout that my view is in is oriented to “vertical”)
Can anyone give me some pointers in how to control the size of my View? For example, how does my custom view know what parameters were set in the XML file?
Android cannot detect the contents of your
Canvas, so it assumes the contents are 0x0.To do what you’re looking for, you have to override
onLayoutoronMeasure(onLayoutis specified by Android developers as a way to lay out children instead). You will also need a way to calculate the size of your contents.First, start with a member variable called
Point mSize = new Point(0, 0);. In a method other thanonDraw, but called just as often, you will want to replace this with the size of your contents. If you draw a circle that has a radius of 25, do:mSize.x = 50; mSize.y = 50;.Next, I’ll introduce you to this answer (for
onMeasure). It shows how to set the size of an item based on its parent’s dimensions (divided by 2, in this case). Then, you can pull the size frommSize.xandmSize.yand apply those dimensions.Finally, calling
invalidate()after you measure your newmSizeshould force theViewto lay itself out again, and adjust to your new parameters. This is the one part I’m unsure of in this regard.NB: Also, you could call
setLayoutParamsusing a fixed width and height once you calculate the size of yourCanvascontents. Not sure of the performance implications for this, though.