Is there a way to animate only the TextView's text size without scaling the entire TextView's layout?
Am trying to achieve a similar effect, Note the text re-sizes to a single line while its size becomes smaller.
Is there a way to animate only the TextView's text size without scaling the entire TextView's layout?
Am trying to achieve a similar effect, Note the text re-sizes to a single line while its size becomes smaller.
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
TextView.getTextSize()
returns the size in dp
, so leaving it to the default value may result in an unwanted effect. So setting the startSize
manually to "sp" via tv.textSize / resources.displayMetrics.density
may be desirable.
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)
textView.setMinHeight()
.