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

如何修改 Android 系統 Dialog 標題欄與分隔線的顏色

編輯:關於 Android 程式設計

先來看效果。系統對話框的標題文字是藍色的,下面還有一根藍色的分隔線。做主題換膚時,這兩個顏色往往必須一起改;但又實在懶得為此定制一整套 Dialog,於是有了下面這個取巧的辦法。

public static void dialogTitleLineColor(Dialog dialog, int titleColor, int dividerColor) {
    Context context = dialog.getContext();

    // 修改標題文字顏色
    int titleId = context.getResources()
            .getIdentifier("android:id/alertTitle", null, null);
    TextView title = (TextView) dialog.findViewById(titleId);
    if (title != null) {
        title.setTextColor(titleColor);
    }

    // 修改標題下方的分隔線顏色
    int dividerId = context.getResources()
            .getIdentifier("android:id/titleDivider", null, null);
    View divider = dialog.findViewById(dividerId);
    if (divider != null) {
        divider.setBackgroundColor(dividerColor);
    }
}

這個方法在幹什麼

它借用 Resources.getIdentifier(),在運行期透過字串名稱反查系統資源的數字 ID,再用 findViewById 把對應的 View 撈出來,最後直接改它的屬性。標題文字與分隔線是兩個不同的資源 ID,所以分兩步處理。

使用時機很關鍵:必須在 dialog.show() 之後呼叫,因為對話框的內部 View 是在 show 過程中才被創建並掛載的。放在 show 之前,findViewById 會拿到 null。

Dialog dialog = new AlertDialog.Builder(context)
        .setTitle("提示")
        .setMessage("內容……")
        .create();
dialog.show();
dialogTitleLineColor(dialog, ContextCompat.getColor(context, R.color.title),
        ContextCompat.getColor(context, R.color.divider));

舉一反三,但也要知道邊界

想改系統控件的任何屬性,思路都是同一套:取得資源 ID → 取得該資源的實例 → 修改屬性。

不過這招屬於「侵入內部實現」,實戰中請留意幾點:

  • 資源名稱沒有公開承諾。titleDivider 從 API 22 起就被標記為廢棄並在後續版本移除,alertTitle 的結構也隨版本變化。換一個 Android 版本,代碼就可能失效,所以每一處都必須做 null 檢查。
  • 不同主題差異大。DeviceDefault、Material、AppCompat 下的對話框內部結構並不相同。若專案使用 AppCompat,更穩妥的做法是自建 style,用 colorAccent、android:textColorAlertDialogListItem 等公開屬性控制配色。
  • 自定義布局才是長久之計。如果只是想換配色,優先考慮 Theme 覆寫;如果連結構都要改,就果斷自定義 Dialog 或改用 DialogFragment / BottomSheetDialogFragment,後者還能自動處理配置變更與記憶體洩漏。

順帶一提,Android 5.0 之後有了 Material Design,作者也把自己很久以前做的 App 按新風格翻新了一遍,可到應用市場下載體驗。

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