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

Android 自訂對話框(Dialog)的完整實作教學

編輯:關於 Android 程式設計

系統預設的 AlertDialog 樣式未必符合設計稿。要做一個完全自訂的 Dialog,大致分為三步:改寫樣式(style/theme)、準備自訂版面,最後封裝成一個可重複使用的類別。以下逐步說明。

第一步:定義自己的 Dialog 樣式

Android 中所有控制項與 View 的外觀,本質上都是透過 style 決定的。在原始碼的 /frameworks/base/core/res/res/values/themes.xml 中,可以看到系統為 Dialog 預先定義的樣式:

<style name="Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowTitleStyle">@android:style/DialogWindowTitle</item>
<item name="android:windowBackground">@android:drawable/panel_background</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
<item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>

從中可以看到標題樣式、視窗背景、是否浮動等屬性都在這裡決定。既然樣式可以繼承,那麼我們只要建立自己的 styles.xml,繼承 Theme.Dialog 再覆寫需要的屬性即可。

在 res/values 下新增 styles.xml:

<style name="Theme_dialog" parent="@android:style/Theme.Dialog">
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowNoTitle">true</item>
</style>

這裡做了兩件事:把 Dialog 所在 Window 的背景設為透明(相當於 #00000000),並隱藏標題列——系統預設的 Dialog 樣式是帶標題的,將 windowNoTitle 設為 true 即可關掉。自訂樣式到此完成。

第二步:撰寫 Dialog 的版面

新增 layout_dialog.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/pp_bg_dialog"
    android:gravity="center" >

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="正在刪除..."
        android:id="@+id/message" />
</LinearLayout>

這裡用了一個垂直的線性版面並讓子元素置中,內容是一個進度條 ProgressBar 與一段提示文字的 TextView。ProgressBar 直接沿用系統預設樣式即可,效果差異不大。

版面設定的背景 @drawable/pp_bg_dialog 是一張自訂的 Shape 圖形資源,也就是畫面上那個居中的半透明黑色圓角框:

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="10dp"/>
    <solid android:color="#55000000"/>
</shape>

定義一個矩形,加上 10dp 圓角與半透明填充。用 Shape 而非圖片檔的好處是可以任意調參數、不會因螢幕密度不同而失真。

第三步:封裝 CustomDialog 類別

為了後續重複使用,建議繼承 Dialog 封裝成獨立類別,把寬高與樣式都收進建構子裡。

public class CustomDialog extends Dialog {

    private static int default_width = 160;   // 預設寬度
    private static int default_height = 120;  // 預設高度

    public CustomDialog(Context context, int layout, int style) {
        this(context, default_width, default_height, layout, style);
    }

    public CustomDialog(Context context, int width, int height, int layout, int style) {
        super(context, style);
        // 設定內容
        setContentView(layout);
        // 設定視窗參數
        Window window = getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        // 依螢幕密度換算並置中
        float density = getDensity(context);
        params.width = (int) (width * density);
        params.height = (int) (height * density);
        params.gravity = Gravity.CENTER;
        window.setAttributes(params);
    }

    private float getDensity(Context context) {
        Resources resources = context.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        return dm.density;
    }
}

建構子中先設定 contentView,再透過 WindowManager.LayoutParams 指定寬高與置中顯示。之所以要乘上 density,是因為我們希望傳入的是 dp 數值而非實體像素,這樣在不同解析度的裝置上視覺比例才會一致。

使用方式

public class CustomDialogDemoActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.test);

        // 使用預設大小 (160 x 120)
        CustomDialog dialog1 = new CustomDialog(this, R.layout.common_dialog, R.style.Theme_dialog);

        // 指定大小 180 x 180
        CustomDialog dialog2 = new CustomDialog(this, 180, 180,
                R.layout.common_dialog, R.style.Theme_dialog);
        dialog2.show();

        // 若要修改 Dialog 內的某個 View,例如把「正在刪除...」換成「加載中...」
        TextView mMessage = (TextView) dialog2.findViewById(R.id.message);
        mMessage.setText("加載中...");
    }
}

因為 Dialog 本身也是一個 View 容器,呼叫 findViewById() 就能直接取得版面內的子控制項,不必另外定義介面。

延伸提醒

  • 樣式繼承關係要對。parent 若寫成 @android:style/Theme.Dialog,記得同時在 res/values 建立對應資源;若想完全從零開始,也可以改用 android:Theme.Material.Dialog(API 21+)或 Base.Theme.AppCompat.Dialog(AppCompat 專案)。
  • 若要顯示在螢幕整體上層並接收返回鍵,可考慮 DialogFragment。它能把 Dialog 的生命週期與 Activity 綁定,旋轉螢幕時不會因為視角重建而遺失,是目前的標準做法。
  • 背景透明並不代表可以任意形狀。真正決定 Dialog 外觀輪廓的是版面根節點的背景,本例中就是那張圓角 Shape。

大體流程就是這樣,剩下的就看你如何變化版面與動畫,設計出符合需求的對話框了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved