I had a similar issue with a similar situation.
I had to create an anmiation for which I required the height of the view
that is subject to the animation. Within that view
, which is a LinearLayout
may be child view of type TextView
. That TextView
is multi line and the number of lines actually required varies.
Whatever I did I just got the measured height for the view as if the TextView
has just one line to fill. No wonder this worked fine every time when the text happend to be short enough for a single line, but it failed when the text was longer than on line.
I considered this answer: https://mcmap.net/q/80996/-android-getmeasuredheight-returns-wrong-values
But that one did not work too well for me because I am not able to access the embedded TextView
directly from here. (I could have iterated though the tree of child views though.)
Have a look at my code as it works for now:
view
is the view that is to be animated. It is a LinearLayout
(The final solution will be a bit more type save here)
this
is a custom view that contains view
and inherits from LinearLayout
too.
private void expandView( final View view ) {
view.setVisibility(View.VISIBLE);
LayoutParams parms = (LayoutParams) view.getLayoutParams();
final int width = this.getWidth() - parms.leftMargin - parms.rightMargin;
view.measure( MeasureSpec.makeMeasureSpec(width, MeasureSpec.AT_MOST),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
final int targetHeight = view.getMeasuredHeight();
view.getLayoutParams().height = 0;
Animation anim = new Animation() {
@Override
protected void applyTransformation( float interpolatedTime, Transformation trans ) {
view.getLayoutParams().height = (int) (targetHeight * interpolatedTime);
view.requestLayout();
}
@Override
public boolean willChangeBounds() {
return true;
}
};
anim.setDuration( ANIMATION_DURATION );
view.startAnimation( anim );
}
This was nearly it but I made another mistake. Within the view hierarchy there are two custom views involved which are subclasses of LinearLayout
and their xml is merged into with a merge
tag as xml root tag. Within one of these merge
tags I overlooked to set the android:orientation
attribute to vertical
.
That did not bother too much for the layout itself, because within this merged ViewGroup
was just one child ViewGroup
and therfore I could not actually see the wrong orientation on screen. But it was there and sort of broke this layout measurement logic a bit.
In addition to the above it may be required to get rid of all paddings associated with LinearLayout
s and subclasses within the view hierarchy. Replace them by margins, even if you have to wrap another layout around it to make it look the same.