編輯:關於 Android 程式設計
前面兩篇我們拆解了 Activity 的布局加載與繪制流程,對系統界面的顯示機制算是有了整體認識。其實 Android 中所有顯示控件的流程都大同小異——Dialog、PopupWindow、Toast 無一例外。這一篇先從 Dialog 入手。
有朋友可能會問:怎麼不講 Fragment?嚴格說 Fragment 並不是顯示控件,而是顯示組件。Activity、Dialog、PopupWindow、Toast 內部都持有並維護著一個 Window 對象,它既管理著一組 View,也承擔著加載與繪制的職責。而 Fragment 內部並沒有 Window 類型的成員變量,只是一組 View 加上一套生命周期控制,因此不具備獨立繪製的能力,必須依附於 Activity 才能顯示。
title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.mipmap.ic_launcher);
builder.setTitle("this is the title view!!!");
builder.setMessage("this is the content view!!!");
builder.setView(R.layout.activity_second);
builder.setPositiveButton("知道了", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
});

icon、title、message、button 都正常呈現,點擊按鈕後 Dialog 消失。定制 Dialog 時操作會多一些,但主幹流程就是這樣。下面沿著這段代碼往源碼裡走。
Builder 是 AlertDialog 的內部類,負責封裝構造過程:
public Builder(Context context) {
this(context, resolveDialogTheme(context, 0));
}
public Builder(Context context, int themeResId) {
P = new AlertController.AlertParams(
new ContextThemeWrapper(context, resolveDialogTheme(context, themeResId)));
}
關鍵在於 P——它是 AlertParams 類型的成員變量。AlertParams 構造時做了幾件基礎準備:
public AlertParams(Context context) {
mContext = context;
mCancelable = true;
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
再看那些 setXxx 方法,会发现它们高度一致:
public Builder setIcon(@DrawableRes int iconId) {
P.mIconId = iconId;
return this;
}
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
public Builder setView(int layoutResId) {
P.mView = null;
P.mViewLayoutResId = layoutResId;
P.mViewSpacingSpecified = false;
return this;
}
public Builder setPositiveButton(CharSequence text, final OnClickListener listener) {
P.mPositiveButtonText = text;
P.mPositiveButtonListener = listener;
return this;
}
本質就是給 P 的各個字段賦值,並且每個方法都返回 this。這正是鏈式調用(Chaining)的實現方式:
builder.setIcon().setMessage().setTitle().setView().setPositiveButton()...
這種設計模式非常值得借鑑:當一個對象有很多可選配置項、且沒哪一項是必須的,就可以用「set 方法賦值 + 返回自身」的方式讓調用方自由組合,代碼可讀性遠勝於寫一個十幾個參數的構造函數。
public AlertDialog create() {
// Context has already been wrapped with the appropriate theme.
final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if (P.mCancelable) {
dialog.setCanceledOnTouchOutside(true);
}
dialog.setOnCancelListener(P.mOnCancelListener);
dialog.setOnDismissListener(P.mOnDismissListener);
if (P.mOnKeyListener != null) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return dialog;
}
先是 new 了一個 AlertDialog:
AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
super(context, createContextThemeWrapper
? resolveDialogTheme(context, themeResId) : 0, createContextThemeWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
mAlert = new AlertController(getContext(), this, getWindow());
}
super 走的是 Dialog 的構造方法,這裡藏著本文最重要的一點:
Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
// ... 解析主題、構造 mContext
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
final Window w = new PhoneWindow(mContext);
mWindow = w;
w.setCallback(this);
w.setOnWindowDismissedCallback(this);
w.setWindowManager(mWindowManager, null, null);
w.setGravity(Gravity.CENTER);
mListenersHandler = new ListenersHandler(this);
}
Dialog 在構造時直接 new 了一個 PhoneWindow 賦給 mWindow,並把回調設為自己。這就解釋了為什麼說 Dialog 與 Activity 的顯示邏輯同源——兩者都是通過各自的 Window 來完成窗口的加載與展示。
WindowManager 的獲取方式也與 Activity 一致:
public void setWindowManager(WindowManager wm, IBinder appToken,
String appName, boolean hardwareAccelerated) {
mAppToken = appToken;
mAppName = appName;
mHardwareAccelerated = hardwareAccelerated
|| SystemProperties.getBoolean(PROPERTY_HARDWARE_UI, false);
if (wm == null) {
wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
}
mWindowManager = ((WindowManagerImpl) wm).createLocalWindowManager(this);
}
因為傳入的 Context 就是 Activity,所以 Dialog 拿到的 WindowManager 與 Activity 的實際是同一個服務,只是各自 createLocalWindowManager 生成了本地實例。
回到 create(),接著執行 P.apply(dialog.mAlert)——把之前收集的所有參數一次性灌進 AlertController:
public void apply(AlertController dialog) {
if (mCustomTitleView != null) {
dialog.setCustomTitle(mCustomTitleView);
} else {
if (mTitle != null) dialog.setTitle(mTitle);
if (mIcon != null) dialog.setIcon(mIcon);
if (mIconId != 0) dialog.setIcon(mIconId);
if (mIconAttrId != 0) dialog.setIcon(dialog.getIconAttributeResId(mIconAttrId));
}
if (mMessage != null) dialog.setMessage(mMessage);
if (mPositiveButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_POSITIVE,
mPositiveButtonText, mPositiveButtonListener, null);
}
if (mNegativeButtonText != null) { /* 同理 */ }
if (mNeutralButtonText != null) { /* 同理 */ }
if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
createListView(dialog);
}
if (mView != null) {
if (mViewSpacingSpecified) {
dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop,
mViewSpacingRight, mViewSpacingBottom);
} else {
dialog.setView(mView);
}
} else if (mViewLayoutResId != 0) {
dialog.setView(mViewLayoutResId);
}
}
至此,setIcon / setTitle / setMessage 收集的值全部落到了 Dialog 的 mAlert 上。之後設置 cancelable 與各類監聽器,create() 返回一個「有內容但還沒上屏」的 Dialog。
public void show() {
if (mShowing) {
if (mDecor != null) {
if (mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
mWindow.invalidatePanelMenu(Window.FEATURE_ACTION_BAR);
}
mDecor.setVisibility(View.VISIBLE);
}
return;
}
mCanceled = false;
if (!mCreated) {
dispatchOnCreate(null);
}
onStart();
mDecor = mWindow.getDecorView();
// ... 初始化 ActionBar、LayoutParams 的 softInputMode
try {
mWindowManager.addView(mDecor, l);
mShowing = true;
sendShowMessage();
} finally {
}
}
逐段看:mShowing 標記是否正在顯示,首次調用時為 false,跳過上面的分支;接著 dispatchOnCreate:
void dispatchOnCreate(Bundle savedInstanceState) {
if (!mCreated) {
onCreate(savedInstanceState);
mCreated = true;
}
}
mCreated 保證 onCreate 只走一次。AlertDialog 覆寫了它:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
Dialog 自己的 onCreate 是空實現,所以重點在 installContent:
public void installContent() {
/* We use a custom title so never request a window title */
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
int contentView = selectContentView();
mWindow.setContentView(contentView);
setupView();
setupDecor();
}
private int selectContentView() {
if (mButtonPanelSideLayout == 0) {
return mAlertDialogLayout;
}
if (mButtonPanelLayoutHint == AlertDialog.LAYOUT_HINT_SIDE) {
return mButtonPanelSideLayout;
}
return mAlertDialogLayout;
}
mAlertDialogLayout 的來源是:
mAlertDialogLayout = a.getResourceId(
R.styleable.AlertDialog_layout, R.layout.alert_dialog);
也就是 R.layout.alert_dialog。從 mWindow.setContentView 這一步開始,布局內容被加載進 Window,後續的 setupView / setupDecor 負責查找並初始化布局中的各個控件以及 DecorView。
回到 show():dispatchOnCreate 之後調用 onStart(主要處理 ActionBar),構造 WindowManager.LayoutParams,最後執行:
mWindowManager.addView(mDecor, l);
走到這裡,如果讀過上一篇 Activity 繪制流程的文章,後面的路就很清楚了——ViewRootImpl 接手,measure / layout / draw 三步走完,Dialog 就顯示出來了。
最後的 sendShowMessage:
private void sendShowMessage() {
if (mShowMessage != null) {
Message.obtain(mShowMessage).sendToTarget();
}
}
它異步發送一條「Dialog 已顯示」的消息,最終由 ListenersHandler 處理:
private static final class ListenersHandler extends Handler {
private final WeakReference<DialogInterface> mDialog;
public ListenersHandler(Dialog dialog) {
mDialog = new WeakReference<>(dialog);
}
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case DISMISS:
((OnDismissListener) msg.obj).onDismiss(mDialog.get());
break;
case CANCEL:
((OnCancelListener) msg.obj).onCancel(mDialog.get());
break;
case SHOW:
((OnShowListener) msg.obj).onShow(mDialog.get());
break;
}
}
}
為什麼用異步消息而不是直接回調?因為 addView 之後界面才算真正上屏,用消息投遞能確保用戶在 onShow 裡操作界面時是安全的。而 mShowMessage 的來源正是我們設置的監聽器:
public void setOnShowListener(OnShowListener listener) {
if (listener != null) {
mShowMessage = mListenersHandler.obtainMessage(SHOW, listener);
} else {
mShowMessage = null;
}
}
另外注意 ListenersHandler 持有的是 WeakReference,避免 Handler 延遲消息導致 Dialog 無法被回收造成內存洩漏。
如果創建 Dialog 時傳入的 Context 不是 Activity,show() 會直接崩潰:
android.view.WindowManager$BadTokenException:
Unable to add window -- token null is not for an application
at android.view.ViewRootImpl.setView(ViewRootImpl.java:690)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:282)
at android.app.Dialog.show(Dialog.java:298)
原因就在源碼裡:WindowManager.addView 最終會走到 ViewRootImpl.setView,那裡會校驗 mToken。而 Dialog 構造時傳入的 appToken 是 null,只有 Activity 作為 Context 時系統才能提供有效的 token。所以 Dialog 必須用 Activity 的 Context,用 Application Context 或 Service Context 都不行。
1. Dialog 與 Activity 的顯示邏輯相似,內部都持有並維護一個 Window 對象,由它完成界面的加載與顯示。
2. Dialog 中的 Window 與 Activity 中的 Window 同屬一类(PhoneWindow),且都對應一個 WindowManager。
3. 相關類的分工:Dialog 是窗口父類,負責 Window 初始化與公共邏輯;AlertDialog 是具體實現;AlertDialog.Builder 是內部類,負責收集參數;AlertController 是控制類;AlertParams 是參數載體。
4. 完整流程:構造 Builder → 鏈式設置屬性 → create() 生成 Dialog 並套用參數 → show() 觸發 onCreate 加載布局 → WindowManager.addView → ViewRootImpl 完成 measure/layout/draw → 界面顯示 → 異步回調 onShow。
把這條鏈路記住,之後分析 PopupWindow 和 Toast 就會輕鬆很多——本質上都是「拿到一個 Window(或代理),把 DecorView 通過 WindowManager 掛上去」。
用 ActionBar 為標題列加上搜尋與分享操作視窗
Android 3.0 之後,Google 在 UI 導航上做了一系列調整,其中最有感的莫過於 ActionBar 的引入。它取代了 3.0 以前那條只有標題文字的標題列
Android SQLite 入門:從 adb shell 語法複習到增刪改查 API 實作
開發過程中幾乎一定會碰到資料庫操作。Android 系統內建 SQLite,這是一款遵守 ACID 事特性的輕量級關聯式資料庫管理系統,佔用資源極低,能支援 Window
Android 四大組件之 Service:從啟動、綁定到生命週期
Service 是一個可以在後台執行長時間操作、且不提供用戶界面的應用組件。它可以由其他組件啟動,即使用戶切換到別的應用,它依然在後台繼續運行;組件也可以綁定到服務進行交
Fragment 生命週期完全解析
一、Fragment 是什麼 Fragment 自 Android 3.0(Honeycomb)起被引入,主要是為了回應平板等大屏設備上日益複雜的介面需求。當一個 Act