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

AlertDialog 自定義風格的兩種實現:setView 與 getIdentifier

編輯:關於 Android 程式設計

一、問題從哪裡來

對話框在任何一款 App 裡幾乎都少不了,Android 也提供了相當容易上手的 AlertDialog。但真正進入專案就會碰到一些尷尬的需求:想改 NegativeButton 的點擊反饋、想調整標題的字級與顏色、想換掉分隔線的樣式。系統預設樣式能做的事很有限,於是有兩條路可以走。

二、方案一:setView 塞入自定義佈局

先看效果圖,這是微信長按通訊錄時彈出的對話框:

系統自帶的樣式顯然做不出這種效果,因此自寫 xml 佈局,再用 AlertDialog.Builder.setView(View) 塞進去:

<!-- wechat_dialog.xml -->
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:orientation="vertical">

    <TextView
        android:id="@+id/id_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="20dp"
        android:text="曾文明"
        android:textColor="@color/bigColor"
        android:textSize="18sp" />

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="@color/lineColor" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="18dp"
        android:text="修改備註"
        android:textColor="@color/txtColor"
        android:textSize="14sp" />
</LinearLayout>
public static void showWeChatTitleDialog(Context context) {
    AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
    dialogBuilder.create();
    View view = LayoutInflater.from(context).inflate(R.layout.wechat_dialog, null);
    dialogBuilder.setView(view);
    dialogBuilder.show();
}

到這裡為止,只能說明 AlertDialog 用起來不複雜,算不上什麼技巧。接下來才是重點。

三、方案二:直接改造系統原生佈局裡的控件

看第二張效果圖:

很多人會照前面的思路再寫一個佈局,用 setView 塞進去。但這裡示範的是另一種做法:沿用系統 AlertDialog 的佈局,只針對其中的控件做樣式替換。

這樣做的好處很實際:系統的 NegativeButton 與 PositiveButton 已經內建了點擊事件介面,不必自己為兩個按鈕寫監聽器與狀態切換,程式碼量差很多。

改按鈕的字色與背景

AlertDialog 提供了現成的方法取得按鈕:

public Button getButton(int whichButton) {
    return mAlert.getButton(whichButton);
}

於是:

Button mNegativeButton = mAlertDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
mNegativeButton.setTextColor(0xff45c01a);
mNegativeButton.setBackgroundResource(R.drawable.button_selector);

另一顆按鈕同理。但要注意一個細節:必須先呼叫 show() 之後才能取到按鈕,否則會拿到 null。

改標題:靠 getIdentifier 反查資源 ID

接著想改 title 的字色,翻遍 AlertDialog 的原始碼卻找不到類似 getTitleView 的方法。這時需要借助 Resources 的這一個方法:

public int getIdentifier(String name, String defType, String defPackage) {
    if (name == null) {
        throw new NullPointerException("name is null");
    }
    try {
        return Integer.parseInt(name);
    } catch (Exception e) {
        // Ignore
    }
    return mAssets.getResourceIdentifier(name, defType, defPackage);
}

顧名思義,它用來取得資源的識別碼,也就是程式中的唯一 ID。三個參數分別是:

  • name:資源的名稱,例如 @+id/alertTitle 中的 alertTitle。
  • defType:資源型別,例如 id、layout、string。
  • defPackage:資源所在的套件名稱,系統資源就是 android。

於是標題、分隔線、內容區都能拿到:

// 標題
final int titleId = mContext.getResources().getIdentifier("alertTitle", "id", "android");
TextView titleTxt = mAlertDialog.findViewById(titleId);
titleTxt.setTextColor(0xff45c01a);

// 標題下方的分隔線
final int titleDivider = mContext.getResources().getIdentifier("titleDivider", "id", "android");
View titleDividerImg = mAlertDialog.findViewById(titleDivider);
titleDividerImg.setVisibility(View.VISIBLE);
titleDividerImg.setBackgroundColor(0xff45c01a);

// 內容面板
final int contentPanel = mContext.getResources().getIdentifier("contentPanel", "id", "android");
LinearLayout contentPanelLayout = mAlertDialog.findViewById(contentPanel);
contentPanelLayout.setVisibility(View.VISIBLE);

// 內容文字
final int message = mContext.getResources().getIdentifier("message", "id", "android");
TextView messageTextView = mAlertDialog.findViewById(message);
messageTextView.setTextSize(TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_SP, 20, mContext.getResources().getDisplayMetrics()));
messageTextView.setPadding(20, 20, 20, 20);
messageTextView.setVisibility(View.VISIBLE);

既然標題和分隔線都能這樣取,按鈕自然也可以,效果與前面用 getButton 是一致的:

final int button1 = mContext.getResources().getIdentifier("button1", "id", "android");
Button negativeButton = mAlertDialog.findViewById(button1);
negativeButton.setBackgroundResource(R.drawable.button_selector);
negativeButton.setVisibility(View.VISIBLE);
negativeButton.setTextColor(0xff45c01a);

final int button2 = mContext.getResources().getIdentifier("button2", "id", "android");
Button positiveButton = mAlertDialog.findViewById(button2);
positiveButton.setBackgroundResource(R.drawable.button_selector);
positiveButton.setVisibility(View.VISIBLE);
positiveButton.setTextColor(0xff45c01a);

第二張效果圖,完全是靠系統自帶的對話框佈局完成的。

四、歸納與風險提示

整篇文章的核心其實只有一個方法:

public int getIdentifier(String name, String defType, String defPackage)

掌握它,改造 AlertDialog 各個控件就不成問題。想熟悉系統佈局到底定義了哪些 View,可以直接去看 alert_dialog.xml,路徑是 //device/apps/common/res/layout/alert_dialog.xml(也就是 frameworks/base/core/res/res/layout/alert_dialog.xml)。

不過這種做法有明確的代價,必須誠實說明:它依賴的是系統內部資源名稱,這些名稱屬於非公開實作,不同 Android 版本、不同廠商定制 ROM 之間都可能改變。一旦某個 ID 查不到(getIdentifier 回傳 0),findViewById 就會得到 null,後續操作直接空指針。因此正式專案中的建議是:

  • 所有 findViewById 的結果都做 null 檢查,取不到就跳過該項樣式調整,讓對話框退回預設外觀而不是崩潰。
  • 把「依系統版本/機型調整樣式」這件事視為增量的裝飾,不要讓核心流程依賴它。
  • 如果設計稿要求高度還原,優先考慮自定義 Dialog 或目前主流的 DialogFragment,可控性遠高於改系統佈局。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved