Andriod中为Dialog设置动画

因为Dialog不属于View,所以不能使用View.startAnimation()。
看了Dialog的源码发现,Dialog其实是Window实现的。所以我们可以使用Window设置动画的方式来实现。

我们这里使用AlertDailog,实现从顶部弹入,隐藏时回到顶部消失。


首先定义2个动画xml

anim_in

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">
    <translate
        android:fromYDelta="-50%p"
        android:toYDelta="0" />
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0" />
</set>

anim_out

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">
    <translate
        android:fromYDelta="0"
        android:toYDelta="-50%p" />
    <alpha
        android:fromAlpha="1.0"
        android:toAlpha="0.0" />
</set>

增加一个样式,引用2个动画

windowEnterAnimation是显示时的动画
windowExitAnimation是隐藏时的动画

    <style name="CustomDialog">
        <item name="android:windowEnterAnimation">@anim/anim_in</item>
        <item name="android:windowExitAnimation">@anim/anim_out</item>
    </style>

为AlertDialog添加动画

        //创建builder
        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setMessage("message").setTitle("标题")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
        //创建AlertDialog
        AlertDialog alertDialog = builder.create();
        //获取Diloag所在的Window
        Window window = alertDialog.getWindow();
        //为Window设置动画
        window.setWindowAnimations(R.style.CustomDialog);
        //显示Dialog
        alertDialog.show();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值