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

去掉自訂 Dialog 白色邊框:透過 Style 覆寫 windowBackground

編輯:關於 Android 程式設計

自訂 Dialog 時最惱人的就是邊上那圈白框,怎麼調版面都拿不掉。其實它是「視窗背景」而不是版面背景,所以要在 style 裡動手腳。

步驟一:在 values 目錄建立 styles.xml

定義一個繼承 Theme.Dialog 的樣式,把視窗相關的裝飾全部關掉:

<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="https://schemas.android.com/apk/res/android">

    <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:windowBackground 設為 @null,同時把 windowFrame 也設為 @null 拿掉邊框;windowNoTitle 則是去掉預設的標題列。

步驟二:建立 Dialog 時帶入這個 style

ProgressDialog dialog = new ProgressDialog(ProgressBarActivity.this, R.style.dialog);

用這個建構子把自訂樣式傳進去,白邊就不會再出現了。

補充一點:backgroundDimEnabled 設為 false 會一併關掉 Dialog 背後的遮罩變暗效果。如果你希望背景仍舊變暗、只是不想要白框,把這個項目留著或設為 true 即可,兩者並不衝突。

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