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