How to stop animation from repeating - Layout anim

2019-08-11 03:54发布

问题:

I'm trying to animate(fade out+pop-in) a couple of text views inside a relative layout on a button click. But after all the text views are done animating, the animation is repeating again. Can someone help me to stop it from repeating. Below is my code.

Also please let me know if any other resources are required.

Activity.kt (Inside onCreate method)

createTextViews() // dynamic creation of textviews
animateView(relLayout,R.anim.pop_in_fadein,1)

//
// some other code
//

btnCancel1.setOnClickListener(View.OnClickListener {
                    animateView(relLayout,R.anim.pop_in_fadeout,0) //0 here is the direction of animation

                    val handler = Handler()
                    handler.postDelayed(Runnable { finish() }, 1150) 
// I'm trying to explicitly stop the animation by closing the activity which shouldn't be done 
                })

 private fun animateView(viewGroup: RelativeLayout?,resource:Int, direction:Int) {
        val animation = AnimationUtils.loadAnimation(this, resource)
        animation.startOffset = 750L

        val controller = LayoutAnimationController(animation)
        controller.delay = 0.1f

        // 0 for normal direction, 2 for random and 1 for reverse direction
        // the direction in which the child views are created
        controller.order = direction

        viewGroup?.setLayoutAnimation(controller)
        viewGroup?.startLayoutAnimation()
    }

pop_in_fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android"
        android:interpolator="@android:anim/overshoot_interpolator">

        <scale
            android:duration="300"
            android:fromXScale="1.0"
            android:fromYScale="1.0"
            android:pivotX="50%"
            android:pivotY="50%"
            android:toXScale="0.0"
            android:toYScale="0.0" />

        <alpha
            android:duration="500"
            android:fromAlpha="1.0"
            android:toAlpha="0.0" />

    </set>

pop_in_fade_in.xml

<scale
    android:duration="300"
    android:fromXScale="0.0"
    android:fromYScale="0.0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1.0"
    android:toYScale="1.0" />

<alpha
    android:duration="500"
    android:fromAlpha="0.0"
    android:toAlpha="1.0" />

回答1:

After running your code in the emulator I think the Animation did finish but the Views kept popping in because a View animation does not make the final state permanent unless you request it by writing (in the Kotlin code)

  animation.fillAfter = true

or by adding android:fillAfter as attribute to the xml file in res/anim

See also the documentation on android:fillAfter respectively setFillAfter()