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

Android 源碼剖析:深入淺出理解 AlertController 的運作機制

編輯:關於 Android 程式設計

在先前分析 AlertDialog 與 AlertDialog.Builder 的文章中我們提到,Builder 中的絕大多數功能其實是透過 AlertController 這個內部類來實現的。它位於 com.android.internal.app 套件中,無法在 Eclipse 裡直接追蹤源碼,因此本文借助 Source Insight 來一探究竟。

私有成員變量的意義

先來看 AlertController 類中的私有成員變量。其中幾個關鍵的佈局相關變量為:

  • mAlertDialogLayout:AlertDialog 的整體佈局。
  • mListLayout:列表佈局。
  • mMultiChoiceItemLayout:多選項目的佈局。
  • mSingleChoiceItemLayout:單選項目的佈局。
  • mListItemLayout:一般 list item 的佈局。

按鈕點擊的事件處理

類中定義了一個自訂的 View.OnClickListener,其目的在於把點擊對象的資訊透過 Message 發送到對應的執行緒(UI 執行緒):

View.OnClickListener mButtonHandler = new View.OnClickListener() {
    public void onClick(View v) {
        Message m = null;
        if (v == mButtonPositive && mButtonPositiveMessage != null) {
            m = Message.obtain(mButtonPositiveMessage);
        } else if (v == mButtonNegative && mButtonNegativeMessage != null) {
            m = Message.obtain(mButtonNegativeMessage);
        } else if (v == mButtonNeutral && mButtonNeutralMessage != null) {
            m = Message.obtain(mButtonNeutralMessage);
        }
        if (m != null) {
            m.sendToTarget();
        }
        // 在上面的處理完成後,再發送一個關閉對話框的訊息
        mHandler.obtainMessage(ButtonHandler.MSG_DISMISS_DIALOG, mDialogInterface)
                .sendToTarget();
    }
};

這段邏輯先取得點擊對應的 Message 並發送到目標執行緒,接著再發送一個訊息通知 UI 執行緒關閉對話框。其中用到的 MSG_DISMISS_DIALOG 定義在內部的 ButtonHandler 類中:

private static final class ButtonHandler extends Handler {
    private static final int MSG_DISMISS_DIALOG = 1;
    private WeakReference<DialogInterface> mDialog;

    public ButtonHandler(DialogInterface dialog) {
        mDialog = new WeakReference<DialogInterface>(dialog);
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case DialogInterface.BUTTON_POSITIVE:
            case DialogInterface.BUTTON_NEGATIVE:
            case DialogInterface.BUTTON_NEUTRAL:
                ((DialogInterface.OnClickListener) msg.obj).onClick(mDialog.get(), msg.what);
                break;
            case MSG_DISMISS_DIALOG:
                ((DialogInterface) msg.obj).dismiss();
        }
    }
}

其邏輯十分清晰:若收到的訊息是 BUTTON_POSITIVE、BUTTON_NEGATIVE 或 BUTTON_NEUTRAL,就回應對應的 OnClick 事件;若是 MSG_DISMISS_DIALOG,則關閉對話框視窗。

構造函數與佈局初始化

AlertController 的構造函數會透過 TypedArray 讀取各項佈局資源 ID,完成初始化:

public AlertController(Context context, DialogInterface di, Window window) {
    mContext = context;
    mDialogInterface = di;
    mWindow = window;
    mHandler = new ButtonHandler(di);

    TypedArray a = context.obtainStyledAttributes(null,
            com.android.internal.R.styleable.AlertDialog,
            com.android.internal.R.attr.alertDialogStyle, 0);

    mAlertDialogLayout = a.getResourceId(
            com.android.internal.R.styleable.AlertDialog_layout,
            com.android.internal.R.layout.alert_dialog);
    mListLayout = a.getResourceId(
            com.android.internal.R.styleable.AlertDialog_listLayout,
            com.android.internal.R.layout.select_dialog);
    // ...其餘佈局資源初始化
    a.recycle();
}

視圖安裝與內容設定

installContent() 方法負責將系統的 AlertDialog 佈局設定為視圖內容,並呼叫 setupView() 完成各部分的配置:

public void installContent() {
    // 無標題模式
    mWindow.requestFeature(Window.FEATURE_NO_TITLE);
    // 如果視圖為空或不是可編輯控件,自動隱藏軟鍵盤
    if (mView == null || !canTextInput(mView)) {
        mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
                WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
    }
    // 設定系統 AlertDialog 為視圖
    mWindow.setContentView(mAlertDialogLayout);
    setupView();
}

而 setupView() 又會依序呼叫 setupContent()、setupButtons()、setupTitle() 與 setBackground() 等方法,分別負責內容區、底部按鈕、標題區與背景的配置。

按鈕區域的設定邏輯

setupButtons() 使用位元運算來追蹤目前顯示了哪些按鈕,並在只有單一按鈕時將其置中:

private boolean setupButtons() {
    int BIT_BUTTON_POSITIVE = 1;
    int BIT_BUTTON_NEGATIVE = 2;
    int BIT_BUTTON_NEUTRAL = 4;
    int whichButtons = 0;
    // ...依序判斷各按鈕文字是否為空,決定顯示或隱藏
    return whichButtons != 0;
}

當只有一個按鈕時,會透過 centerButton() 將其水平置中,並佔據可用區域的一半。

標題與背景的处理

setupTitle() 的邏輯是:若設定了自訂頂部視圖,就直接使用自訂視圖並隱藏標題模板;否則使用預設視圖顯示標題文字與圖示,若沒有標題文字,也一併隱藏標題模板。

setBackground() 則是整個流程中較為複雜的一環。它會先取得各種背景資源(如全暗、頂部暗、中央暗、底部暗,以及對應的明亮版本),再把各個區塊收集到陣列中,依據「明暗」與「位置(頂部、中央、底部)」來套用正確的背景圖。核心概念在於:內容區若顯示文字應使用深色背景,若顯示 ListView 則使用淺色背景;而底部按鈕區則使用偏中色的背景。

AlertParams:Builder 的參數工具類

最後定義的靜態內部類 AlertParams,可以視為 AlertController 的參數工具類。它保存了標題、圖示、訊息、按鈕文字與監聽器、列表項目、多選/單選狀態等大量參數,並透過兩個關鍵方法發揮作用:

  • apply(AlertController dialog):把 AlertParams 中收集到的各項設定逐一套用至 AlertController,這是在 AlertDialog.Builder 的 create() 方法中呼叫的。
  • createListView(AlertController dialog):根據是否為多選、是否使用 Cursor 資料來源等情況,建立對應的 Adapter 與 RecycleListView,並設定單選或多選模式。

值得注意的是,程式刻意不直接為 ListView 設定 Adapter,而是先存到 dialog.mAdapter,因為後續可能還需要為 ListView 加上頁腳(footer)。

總結來說,如果想深入理解 AlertDialog 的運作,建議搭配 AlertDialog 的源碼一起閱讀,因為 AlertDialog 中的絕大部分功能,其實都是靠呼叫 AlertController 這個內部類來完成的。

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