Justin McGuire
Justin McGuire

Reputation: 365

android - smooth animation of changing height of a view

I wanted to animate changing height of a TextView from 0 to its real height. I'm using this code:

ValueAnimator anim = ValueAnimator.ofInt(0, height)
                        .setDuration(1000);
                anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                    public void onAnimationUpdate(ValueAnimator animation) {
                        textView.getLayoutParams().height = (int)animation.getAnimatedValue();
                        textView.requestLayout();
                    }
                });
                anim.start();

But the animation is not that smooth (not awful, but I think it can be smoother).

What are the ways to make the smoothest animations of this sort?

Upvotes: 3

Views: 6274

Answers (2)

sanjay
sanjay

Reputation: 636

Try the below codes. I hope it will help you.

textView.setScaleY(0);
textView.setScaleX(0);

textView.animate()
                .scaleY(1)
                .scaleX(1)
                .setDuration(200)
                .setInterpolator(INTERPOLATOR)
                .start();

Declare INTERPOLATOR as a class level variable like below code.

private static final Interpolator INTERPOLATOR = new DecelerateInterpolator();

This will give you a very smooth animation. And you can play with this piece of code and can animate as you need.You can change the INTERPOLATOR. Learn more about INTERPOLATOR.

Upvotes: 0

Ragesh Ramesh
Ragesh Ramesh

Reputation: 3520

The reason for its not smooth is because you are setting layout height in each update call and requesting layout too which can be cpu intensive when done several times in a second. The more smoother way i can suggest is Keeping the textview visibility as gone and then setting it to visible in code.

Then you can animate the transition using animation set. Also if you dont want to customise the animation and only want it to animate into position you can use default animation by specifying below xml attribute to the parent layout of your textview

    android:animateLayoutChanges= "true"

Then when you set Visibility as visible in your code like below

    textview.setVisibility(View.VISIBLE)

Your textview will automatically animate into its place.

Upvotes: 1

Related Questions