Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

為 Android Dialog 加上進出場動畫

編輯:關於 Android 程式設計

Dialog 並不繼承自 View,所以一般對 View 使用的 startAnimation() 在它身上是行不通的。翻一下 Dialog 的原始碼就會發現,Dialog 內部其實是由 Window 實作的,因此正確的做法是透過 Window 的 API 來設定動畫。

下面示範一個 AlertDialog 從頂部彈入、關閉時回到頂部消失的效果。

步驟一:定義兩份動畫 XML

res/anim/anim_in.xml —— 進場動畫

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

res/anim/anim_out.xml —— 退場動畫

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

進場從螢幕上方外側滑入並淡入,退場則反向滑回上方並淡出。若想要不同的手感,把 translate 的 Y 軸改成其他比例即可。

步驟二:新增一個 Style 引用這兩份動畫

關鍵在於兩個屬性:android:windowEnterAnimation 對應顯示時的動畫,android:windowExitAnimation 對應隱藏時的動畫。

<style name="CustomDialog" parent="android:style/Theme.Dialog">
    <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();

// 取得 Dialog 所在的 Window
Window window = alertDialog.getWindow();

// 為 Window 設定動畫樣式
window.setWindowAnimations(R.style.CustomDialog);

// 顯示
alertDialog.show();

幾個實務提醒

  • 一定要在 show() 之前設定 windowAnimations,顯示後再設不會有效果。
  • 如果不想寫 XML,也可以直接呼叫 window.setWindowAnimations() 傳入程式動態產生的 Animation 資源 id。
  • 自訂 Dialog(直接繼承 Dialog 類別)用法完全相同,一樣是透過 getWindow() 取得視窗後設定。
  • 動畫時長建議控制在 300~500ms,過長會讓互動感覺遲鈍。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved