TextView的文本大小的动画,而不是整个TextView的动画

coz*_*eJ4 16 android textview android-layout

有没有办法只动画TextView的文本大小而不缩放整个TextView的布局?

在此输入图像描述

我试图获得类似的效果,请注意文本在其大小变小时重新调整为单行.

kor*_*rre 33

这可以通过ValueAnimator我的头顶来实现,我觉得它应该是这样的:

final TextView tv = new TextView(getApplicationContext());

final float startSize = 42; // Size in pixels
final float endSize = 12;
long animationDuration = 600; // Animation duration in ms

ValueAnimator animator = ValueAnimator.ofFloat(startSize, endSize);
animator.setDuration(animationDuration);

animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator valueAnimator) {
        float animatedValue = (float) valueAnimator.getAnimatedValue();
        tv.setTextSize(animatedValue);
    }
});

animator.start();
Run Code Online (Sandbox Code Playgroud)


Nic*_*sco 8

作为对@korrekorre 回答的跟进:文档建议使用更简单的ObjectAnimator API

final TextView tv = new TextView(getApplicationContext());

final float endSize = 12;
final int animationDuration = 600; // Animation duration in ms

ValueAnimator animator = ObjectAnimator.ofFloat(tv, "textSize", endSize);
animator.setDuration(animationDuration);

animator.start();    
Run Code Online (Sandbox Code Playgroud)

只有一个警告:您传递给构造函数的属性("textSize"在本例中)必须具有公共 setter 方法才能使其工作。

您也可以将 a 传递startSize给构造函数,如果不这样做,则插值器将使用当前大小作为起点

  • 另一件需要注意的事情是:`TextView.getTextSize()` 返回以 `dp` 为单位的大小,因此将其保留为默认值可能会导致不必要的效果。因此,通过“tv.textSize / resources.displayMetrics.密度”手动将“startSize”设置为“sp”可能是可取的。 (2认同)