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?
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_parentsituation than awrap_contentsituation). These constraints are packaged up into theMeasureSpecvalues that are passed into the method. Here is a rough correlation of the mode values:layout_widthorlayout_heightvalue was set to a specific value. You should probably make your view this size. This can also get triggered whenmatch_parentis used, to set the size exactly to the parent view (this is layout dependent in the framework).layout_widthorlayout_heightvalue was set tomatch_parentorwrap_contentwhere 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_widthorlayout_heightvalue was set towrap_contentwith 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 callsuperinstead 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_contentin 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
Viewand not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this: