您的位置:首页 > 移动开发 > Android开发

Andriod中为Dialog设置动画

2016-12-05 00:27 483 查看
因为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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息