因爲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();