简体   繁体   中英

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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM