2016-08-23 90 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); 
    } 
} 

即可設置相應的參數,它應該完成這項工作。希望能幫助到你。