I have an activity with a couple of views in a linear layout, one is a textview and one is the main view of my game, which is a custom view I do things with in code.
When I added the following piece of code into my activity:
mTextView.setText("random text");
The onMeasure() is being called in the custom view, i.e. setText on the textview seems to be causing a different view to re-measure.
Because my onmeasure() code resets the view in a undesirable way, I want to avoid this happening.
What is causing the call to onMeasure() in this case and how can I stop it?
Answer to your question:
In a linear layout, the size and position of each element depends on the sizes and positions of the elements that come before it. If you use layout weights to size the elements instead of using fixed sizes, moreover, then an element’s size and position also depends on the elements that come after it.
Changing the contents of one element (in your case by calling
setText()) may change the size of that element. As a result, Android does a re-layout to determine the new sizes and positions for the LinearLayout’s children, and this requires all the elements in the linear layout to be measured.Answer to your problem:
It would be wise to assume that
onMeasure()can be called at any time. A good solution would be to changeonMeasure()so that it has no side-effects. Instead wait foronSizeChanged()before you “reset the view.”