萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 自定義 Dialog:Style 主題與 Shape 繪製圓角背景

系統預設 Dialog 風格單一,透過 style 主題與 shape 可輕鬆實現圓角、邊框、內距、背景色完全自訂的對話框。

Step 1:定義 Shape 背景

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" android:color="#00FFFF80" /> <!-- 邊框:半透明青 -->
    <corners android:radius="2dp" />              <!-- 圓角半徑 -->
    <padding android:left="10dp" android:top="10dp"
           android:right="10dp" android:bottom="10dp" /> <-- 內容邊距 -->
</shape>
  • solid:填充顏色;
  • stroke:描邊寬度與顏色;
  • corners:統一圓角或分別指定 topLeftRadius 等;
  • padding:內容區與邊框距離。

Step 2:定義 Dialog 主題

res/values/styles.xml

<resources>
    <style name="Theme.CustomDialog" parent="android:style/Theme.Dialog">
        <item name="android:windowBackground">@drawable/filled_box</item>
        <item name="android:windowNoTitle">true</item>        <!-- 隱藏標題欄 -->
        <item name="android:windowIsFloating">true</item>     <-- 浮動窗口 -->
    </style>
</resources>
  • 繼承 Theme.Dialog 保留對話框語義(模態、浮動、陰影);
  • windowBackground 套用自訂 Shape;
  • 可追加 windowAnimationStyle 自定進出動畫。

Step 3:套用至 Activity 或 Dialog

方式 A:以 Activity 形式呈現(Manifest 宣告)

<activity
    android:name=".CustomDialogActivity"
    android:theme="@style/Theme.CustomDialog" />

方式 B:程式碼建立 Dialog(更靈活)

Dialog dialog = new Dialog(context, R.style.Theme_CustomDialog);
dialog.setContentView(R.layout.custom_dialog_layout); // 自訂佈局
dialog.show();

進階:DialogFragment 現代寫法

public class CustomDialogFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = new Dialog(requireContext(), R.style.Theme_CustomDialog);
        dialog.setContentView(R.layout.custom_dialog_layout);
        // 綁定 View、設定監聽器...
        return dialog;
    }

    @Override
    public void onStart() {
        super.onStart();
        // 設定寬度佔螢幕 90%
        Window window = getDialog().getWindow();
        if (window != null) {
            window.setLayout((int)(Resources.getSystem().getDisplayMetrics().widthPixels * 0.9),
                             WindowManager.LayoutParams.WRAP_CONTENT);
        }
    }
}

優缺點比較

方式優點缺點
Theme + Activity簡單、全螢幕對話框生命週期較重、難以復用
Theme + Dialog輕量、可複用需自行管理 show/dismiss
DialogFragment生命週期感知、配置變更自動恢復、支援返回棧代碼稍多

新專案強烈建議採用 DialogFragment。

copyright © 萬盛學電腦網 all rights reserved