You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何为Alert Dialog实现整体抖动动画效果

Alert Dialog 整体抖动实现方案

核心实现逻辑为给弹窗的根容器添加位移动画,通过短时间内的往复偏移形成抖动效果,各端实现方式如下:


Android 平台实现

  • 首先在res/anim目录下创建抖动动画配置文件dialog_shake.xml
<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="100"
    android:fromXDelta="0"
    android:interpolator="@android:anim/cycle_interpolator"
    android:cycles="3"
    android:toXDelta="10" />
  • 点击按钮触发抖动的逻辑:
// 构建并显示AlertDialog
val alertDialog = AlertDialog.Builder(this)
    .setTitle("提示")
    .setMessage("弹窗内容")
    .setPositiveButton("确定", null)
    .show()

// 触发按钮点击事件绑定
shakeTriggerBtn.setOnClickListener {
    val shakeAnim = AnimationUtils.loadAnimation(this, R.anim.dialog_shake)
    // 获取弹窗根View启动动画,实现整体抖动
    alertDialog.window?.decorView?.startAnimation(shakeAnim)
}

注意不要仅给弹窗内的文字控件设置动画,必须绑定到弹窗对应的Window根DecorView才能实现整体抖动


前端Web 原生实现

  • 先定义抖动CSS动画:
@keyframes dialog-shake {
    0%, 100% { transform: translateX(0); }
    25% { transform: translateX(-10px); }
    75% { transform: translateX(10px); }
}
.shake {
    animation: dialog-shake 0.3s linear 3;
}
  • 点击触发逻辑:
const triggerBtn = document.querySelector('#shake-trigger')
const alertDialog = document.querySelector('.alert-dialog') // 替换为你的弹窗根节点选择器

triggerBtn.addEventListener('click', () => {
    // 移除后重新添加类名保证重复点击可重复触发
    alertDialog.classList.remove('shake')
    void alertDialog.offsetWidth // 主动触发重绘
    alertDialog.classList.add('shake')
})

iOS 平台实现

// alertController为已经创建并显示的UIAlertController实例
let shakeTriggerBtn = UIButton()
shakeTriggerBtn.addTarget(self, action: #selector(triggerDialogShake), for: .touchUpInside)

@objc func triggerDialogShake() {
    guard let dialogRootView = alertController.view else { return }
    let shakeAnim = CABasicAnimation(keyPath: "position.x")
    shakeAnim.duration = 0.1
    shakeAnim.repeatCount = 3
    shakeAnim.autoreverses = true
    shakeAnim.fromValue = dialogRootView.center.x - 10
    shakeAnim.toValue = dialogRootView.center.x + 10
    dialogRootView.layer.add(shakeAnim, forKey: "dialog_shake_anim")
}

内容的提问来源于stack exchange,提问作者gurkan stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 08:06:04