Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to apply animation when I press back button for component of Activity in Kotlin?

I want to apply animation when I press back button from fragment.

For this, I know that I can use overridePendingTransition like below.

override fun finish() {
        super.finish()
        overridePendingTransition (0, R.anim.slide_down_enter)
    }

Then I can apply animation before closing this fragment.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

However this works for all fragment (or activity).

I want to apply only one View of this fragment, but overridePendingTransition doesn’t provides such function.

I tried to give pending like below in onBackPressed.

override fun onBackPressed() {
        super.onBackPressed()
        resumePause = true

        var downAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_down_enter)
        binding.commentLayout.startAnimation(downAnimation)

        Handler().postDelayed({
            finish()
        }, 500)
    }

But It also doesn’t work.

Is there any way to do this?

>Solution :

Hey you can override the onBackPressed method in your activity and apply the animation to the view you want to animate.

Here’s an example:

override fun onBackPressed() {
    val downAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_down_enter)
    binding.commentLayout.startAnimation(downAnimation)
    downAnimation.setAnimationListener(object : Animation.AnimationListener {
        override fun onAnimationStart(animation: Animation?) {}

        override fun onAnimationEnd(animation: Animation?) {
            finish()
            overridePendingTransition(0, R.anim.slide_down_enter)
        }

        override fun onAnimationRepeat(animation: Animation?) {}
    })
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading