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

Android Dialog 去除白色邊框的實作思路與程式碼

編輯:關於 Android 程式設計

問題來源

Android 的 Dialog 預設會帶一圈白色邊框,自訂版面時常常顯得突兀。要拿掉它,得先理解 Dialog 的樣式是怎麼套上的。

一、定義自訂樣式

在 values 目錄下新增 styles.xml:

<resources>
    <style name="dialog" parent="@android:style/Theme.Dialog">
        <item name="android:windowFrame">@null</item>
        <item name="android:windowIsFloating">true</item>
        <item name="android:windowIsTranslucent">false</item>
        <item name="android:windowNoTitle">true</item>
        <item name="android:background">@android:color/black</item>
        <item name="android:windowBackground">@null</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>
</resources>

其中真正消除邊框的關鍵是兩行:android:windowFrame 設為 @null,以及 android:windowBackground 設為 @null。前者拿掉視窗外框,後者拿掉那張帶邊框的 nine-patch 背景圖。

二、套用樣式建立 Dialog

使用 Dialog 的建構子並指定樣式資源即可:

Dialog dialog = new Dialog(SetActivity.this, R.style.dialog);
dialog.setContentView(R.layout.test);
dialog.show();

三、從原始碼看原因

翻開 Dialog 的原始碼,帶樣式參數的建構子長這樣:

public Dialog(Context context, int theme) {
    mContext = new ContextThemeWrapper(
            context, theme == 0 ? com.android.internal.R.style.Theme_Dialog : theme);
    mWindowManager = (WindowManager) context.getSystemService("window");
    Window w = PolicyManager.makeNewWindow(mContext);
    mWindow = w;
    w.setCallback(this);
    w.setWindowManager(mWindowManager, null, null);
    w.setGravity(Gravity.CENTER);
    mUiThread = Thread.currentThread();
    mDismissCancelHandler = new DismissCancelHandler(this);
}

可以清楚看到:當 theme 參數為 0 時,系統會退回使用預先寫好的 Theme_Dialog 樣式。而 Dialog 的外觀其實是由多張 9.png 圖片拼出來的,其中大部分都帶有邊框——這就是為什麼前面必須把背景與視窗外框都設成 @null,才能徹底擺脫那圈白邊。

四、效果對比

設定之前:

設定之後:

這個小細節當初折騰了筆者不少時間,希望這份整理能幫你少走一點彎路。

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