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

Animation of a TextView's text size and not the entire TextView

有没有办法在不缩放整个 TextView 布局的情况下仅对 TextView 的文本大小进行动画处理?

我正在尝试实现类似的效果,请注意,文本会在变小的同时调整为单行。

这可以通过 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();

作为@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();    

只有一个警告:您传递给构造函数的 属性(在本例中为 "textSize"必须 有一个 public setter 方法使其起作用。

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

使用 Kotlin,创建如下扩展函数:

fun TextView.sizeScaleAnimation(endSize: Float, durationInMilliSec: Long) {
    val animator = ObjectAnimator.ofFloat(this, "textSize", endSize)
    animator.duration = durationInMilliSec
    animator.start()
}

这样使用:

 val endSize = resources.getDimension(R.dimen.my_new_text_size)
 myTextView.sizeScaleAnimation(endSize, 200L)