如何中断对话框动画?DialogFragment在onPause中终止长退出动画的方法
Absolutely, you can interrupt that long exit animation in the onPause() method—this is a clean, lifecycle-compliant fix for the issue where your animation leaks onto the home screen when the user presses the HOME key. Since you need to keep the long animation for normal dismissals, this approach lets you only stop it when the app is sent to the background.
Here's the step-by-step implementation for your DialogFragment:
- Override the
onPause()method in your DialogFragment, making sure to call the superclass implementation first (per Android lifecycle best practices). - Get a reference to your dialog and its window—we need to target the window where the animation is running.
- Clear or reset the window animation to stop it immediately.
Code Implementation
override fun onPause() { super.onPause() // Skip if the dialog is already null or detached val currentDialog = dialog ?: return val dialogWindow = currentDialog.window ?: return // Option 1: Clear all animations on the window's root view dialogWindow.decorView.clearAnimation() // Option 2: Reset window animations to default (no animation) dialogWindow.setWindowAnimations(0) // Optional: If you want to ensure the dialog is fully hidden immediately // currentDialog.dismiss() }
How This Works
When the user presses the HOME key, your DialogFragment's onPause() method is triggered. By clearing the decor view's animation or resetting the window animations to the system default (0 = no animation), you force the ongoing exit animation to stop immediately. This prevents the animation from continuing to render in the background and appearing over the home screen.
If your custom animation used property animations instead of window transition animations, you'd want to hold a reference to the animator instance and call animator.cancel() in onPause()—but since you're using window.setWindowAnimations(), the above code will handle it perfectly.
This approach preserves your long animation for normal dismissals (like when the user taps outside the dialog or presses a cancel button) while fixing the unwanted home screen leak.
内容的提问来源于stack exchange,提问作者Aleksandr Gilmanov

