1. 概述
這節課我們來分析下Builder設計模式中的AlertDialog的源碼,效果圖如下:
AlertDialog源碼分析.png
1>:組裝P里邊的參數,相當于組裝電腦零件,然后返回一個新的 dialog對象
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
// 組裝P里邊的參數,相當于組裝電腦零件
P.apply(dialog.mAlert);
}
return dialog;
2>:組裝
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) {
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, mNegativeButtonText,
mNegativeButtonListener, null);
}
if (mNeutralButtonText != null) {
dialog.setButton(DialogInterface.BUTTON_NEUTRAL, mNeutralButtonText,
mNeutralButtonListener, null);
}
}
組裝的規則就是:有什么就拼裝什么,所以這里就會有一系列的if判斷
3>:最后調用 父類的Dialog的 show()方法
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);
} else {
// Fill the DecorView in on any configuration changes that
// may have occured while it was removed from the WindowManager.
final Configuration config = mContext.getResources().getConfiguration();
mWindow.getDecorView().dispatchConfigurationChanged(config);
}
2. Builder設計模式的工作流程
1>:添加一些參數,到P里邊,就是AlertController.AlertParams;
2>:添加完參數之后就開始組裝,原則就是你添加多少參數我就組裝多少參數;
3>:最后調用 show()方法去顯示 Dialog就可以;
3. 主要的對象
AlertDialog: 電腦對象
AlertDialog.Builder:規范一系列的組裝過程
AlertController:具體的構造器
AlertController.AlertParams:用來存放一些參數,還包含一部分設置參數的功能
基于上邊我們對源碼的分析,那么我們下節課就一起來寫一個 萬能的 Dialog。
自定義萬能的Dialog