Andriod中为Dialog设置动画

来源:互联网 发布:手机搜不到网络 只有2g 编辑:程序博客网 时间:2024/05/16 09:22

因为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 0
原创粉丝点击