2016-08-23 91 views
0

我在LinearLayout中有一个TextView。我的目标是在文本更改并需要更多或更少行时为TextView高度更改设置动画。如何为TextView高度变化设置动画

我这样拆分的工作:

  1. 淡出了旧文本
  2. 动画TextView的新高度(和家长的LinearLayout)在新的文本
  3. 淡出

淡入/淡出部分很容易,但我为高度变化动画而奋斗。

这里是我的简化布局:

<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不会动态变化高度,所以不是一个解决方案,但我没有尝试过。

回答

0

我的问题的解决方案是使用一个虚拟的TextView,并用新的文本而不是使用实际的TextView进行测量。这样,我的TextView在动画之前不会被调整大小,我只需要在动画结尾处设置文本。

查看此答案的详细资料:Getting height of text view before rendering to layout

0

你可以使用一个为此递归运行的处理程序,看起来也有点干净。在您的onCreate

呼叫功能startTextAnimation()

Handler animHandler = new Handler();()

然后使用此功能:所以,举例来说,使用这个

public void startTextAnimation() { 
    textView.setHeight(textView.getHeight() + 1); 
    if (textView.getHeight < *whatheightyouwant*) { 
     aninHandler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       startTextAnimation(); 
      } 
     }, 200); 
    } 
} 

即可设置相应的参数,它应该完成这项工作。希望能帮助到你。