I tried to do custom component. I extended View
class and do some drawing in onDraw
overrided method. Why I need to override onMeasure
? If I didn't, everything seen to be right. May someone explain it? How should I write my onMeasure
method? I've seen couple tutorials, but each one is a little bit different than the other. Sometimes they call super.onMeasure
at the end, sometimes they use setMeasuredDimension
and didn't call it. Where is a difference?
After all I want to use several exactly the same components. I added those components to my XML
file, but I don't know how big they should be. I want to set its position and size later (why I need to set size in onMeasure
if in onDraw
when I draw it, is working as well) in custom component class. When exactly I need to do that?
Best Answer
onMeasure()
is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in amatch_parent
situation than awrap_content
situation). These constraints are packaged up into theMeasureSpec
values that are passed into the method. Here is a rough correlation of the mode values:layout_width
orlayout_height
value was set to a specific value. You should probably make your view this size. This can also get triggered whenmatch_parent
is used, to set the size exactly to the parent view (this is layout dependent in the framework).layout_width
orlayout_height
value was set tomatch_parent
orwrap_content
where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.layout_width
orlayout_height
value was set towrap_content
with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.The contract that exists with
onMeasure()
is thatsetMeasuredDimension()
MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found inView
, which is why it is safe to callsuper
instead if that fits your use case.Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with
wrap_content
in both directions, your view may not show up at all because the framework doesn't know how large it is!Generally, if you are overriding
View
and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:Hope that Helps.