我在LinearLayout中有一個TextView。我的目標是在文本更改並需要更多或更少行時爲TextView高度更改設置動畫。如何爲TextView高度變化設置動畫
我這樣拆分的工作:
- 淡出了舊文本
- 動畫TextView的新高度(和家長的LinearLayout)在新的文本
- 淡出
淡入/淡出部分很容易,但我爲高度變化動畫而奮鬥。
這裏是我的簡化佈局:
<LinearLayout
android:id="@+id/fragment_tooltip_tooltip"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/tooltip_blue_bg"
android:gravity="center_vertical"
android:orientation="horizontal">
<TextView
android:id="@+id/fragment_tooltip_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
這裏是我的嘗試:
final int currentHeight = tvMessage.getHeight();
tvMessage.setText(toTooltip.getMessage());
tvMessage.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
TooltipFragment.this.tvMessage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
final int newHeight = tvMessage.getHeight();
ResizeAnimation resizeAnimation = new ResizeAnimation(tvMessage, tvMessage.getWidth(), tvMessage.getWidth(),
currentHeight, newHeight);
resizeAnimation.setDuration(ANIM_DURATION_TRANSITION_TEXT_RESIZE);
resizeAnimation.setInterpolator(new FastOutSlowInInterpolator());
resizeAnimation.setAnimationListener(new Animation.AnimationListener() {
@Override
public void onAnimationStart(Animation animation) {
// No-op
}
@Override
public void onAnimationEnd(Animation animation) {
// Finally we show the new content
...
}
@Override
public void onAnimationRepeat(Animation animation) {
// No-op
}
});
tvMessage.startAnimation(resizeAnimation);
}
});
這種解決方案的問題是,tvMessage.setText(toTooltip.getMessage());用於測量新高度的直線立即展開TextView和LinearLayout,然後在應用調整動畫大小之前動畫會將視圖調整爲其以前的大小,從而產生難看的視覺效果。
我相信一個TextSwitcher不會動態變化高度,所以不是一個解決方案,但我沒有嘗試過。