Search code examples
javaandroidandroid-activityviewonmeasure

When is View.onMeasure() called?


When is

View.onMeasure(int widthMeasureSpec, int heightMeasureSpec)

called? I have an Activity that needs to perform an action after onMeasure has been called.

My question is the same as the unanswered question posted here. The View documentation states that onMeasure is called when requestLayout() is called, which is apparently called by a view on itself when it believes that is can no longer fit within its current bounds.

However, this doesn't tell me when my activity can assume that my View has been measured. I've used this code to extend ImageView to form TouchImageView. It was suggested here that I should use the onMeasure method to scale my image. I wish to update the value of a TextView after the ImageView has been measured in order to display the percentage by which the image has been scaled.


Solution

  • onMeasure is called when the parent View needs to calculate the layout. Typically, onMeasure may be called several times depending on the different children present and their layout parameters.

    The best way to do something when onMeasure is called is (I think) to create your own control, extend the ImageView and override onMeasure (just call super.onMeasure and do whatever else you would like to do).

    If you do that, just keep in mind that on Measure may be called several times with different parameters, so whatever is measured may not be the final width and height of what will be actually displayed.