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

21

有没有一种方法可以仅对TextView的文本大小进行动画处理,而不会缩放整个TextView的布局?

enter image description here

我试图实现类似的效果,注意文本调整大小为单行,而其大小变小。


使用ObjectAnimator/ValueAnimator - pskink
@pskink,一些更详细的细节会更有帮助。 - cozeJ4
你尝试过设置TextView的固定最小高度吗?textView.setMinHeight() - D-Dᴙum
@Kerry 抱歉,那怎么帮助动画呢? - cozeJ4
误解了你的问题,我以为你不想让文本框的大小随着字体大小的改变而改变。 - D-Dᴙum
3个回答

45

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

9
作为对@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")必须具有公共的setter方法,以使此操作正常工作。

如果没有传递startSize,则插值器将使用当前大小作为起始点。


更高效的解决方案! - Gary Chen
2
另外需要注意的是:TextView.getTextSize() 返回的大小是以 dp 为单位的,因此将其保留为默认值可能会导致不必要的效果。因此,通过 tv.textSize / resources.displayMetrics.density 手动将 startSize 设置为 "sp" 可能更理想。 - Beko
在文本大小方面,使用resources.displayMetrics.scaledDensity代替resources.displayMetrics.density - masoomyf

1
使用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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接