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

Android 自訂對話框:用 Drawable 與 Style 打造專屬外觀

編輯:關於 Android 程式設計

在 Android 中,若要讓 Dialog 呈現不同於系統預設的外觀,可以透過自訂 Drawable 與 Style 來完成。整體概念是先定義一個背景形狀,再建立一個繼承自 Dialog 主題的樣式,最後將樣式套用到 Activity。

建立 Drawable 背景

首先在 res/drawable 目錄建立 filled_box.xml,用來定義對話框背景:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="https://schemas.android.com/apk/res/android">
    <solid android:color="#ffff0000" />
    <stroke android:width="3dp" color="#00ffff80" />
    <corners android:radius="2dp" />
    <padding android:left="10dp" android:top="10dp" android:right="10dp" android:bottom="10dp" />
</shape>

這個 shape 預設為矩形,因此沒有特別指定 android:shape。solid 用來設定填滿色,stroke 用來設定邊框,corners 用來設定圓角,padding 則控制內容與邊界的間距。

建立自訂 Style

接著在 res/values 目錄建立 styles.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="Theme.CustomDialog" parent="android:style/Theme.Dialog">
        <item name="android:windowBackground">@drawable/filled_box</item>
    </style>
</resources>

這裡自訂的主題名稱是 Theme.CustomDialog,parent 指定為 android:style/Theme.Dialog,表示沿用系統 Dialog 的基本行為,再透過 android:windowBackground 把背景換成 filled_box。

套用自訂主題

完成樣式後,在 AndroidManifest.xml 中為要使用自訂對話框的 Activity 加上 android:theme 屬性:

android:theme="@style/Theme.CustomDialog"

執行專案後,即可看到自訂顏色、邊框與圓角的對話框效果。這種做法很適合用來快速調整 Dialog 的視覺風格,也能與後續的版面配置搭配。

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