android – Animation of a TextView's text size and not the entire TextView-ThrowExceptions

Exception or error:

Is there a way to animate only the TextView’s text size without scaling the entire TextView’s layout?

enter image description here

Am trying to achieve a similar effect, Note the text re-sizes to a single line while its size becomes smaller.

How to solve:

This could be achieved with a ValueAnimator and from the top of my head I think it should look something like this:

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();

###

As a follow up on @korrekorre answer: The documentation suggests to use the simpler 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();    

There is just one caveat: The property you pass to the constructor ("textSize" in this case) must have a public setter method for this to work.

You can also pass a startSize to the constructor, if you don’t then the interpolator will use the current size as starting point

###

With Kotlin, create an extension function like this:

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

Use it like this:

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

Leave a Reply

Your email address will not be published. Required fields are marked *