// AlertDialog
public
class
AlertDialog
extends
Dialog
implements
DialogInterface {
// Controller, 接受Builder成员变量P中的各个参数
private
AlertController mAlert;
// 构造函数
protected
AlertDialog(Context context,
int
theme) {
this
(context, theme,
true
);
}
// 4 : 构造AlertDialog
AlertDialog(Context context,
int
theme,
boolean
createContextWrapper) {
super
(context, resolveDialogTheme(context, theme), createContextWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
mAlert =
new
AlertController(getContext(),
this
, getWindow());
}
// 实际上调用的是mAlert的setTitle方法
@Override
public
void
setTitle(CharSequence title) {
super
.setTitle(title);
mAlert.setTitle(title);
}
// 实际上调用的是mAlert的setCustomTitle方法
public
void
setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public
void
setMessage(CharSequence message) {
mAlert.setMessage(message);
}
// AlertDialog其他的代码省略
// ************ Builder为AlertDialog的内部类 *******************
public
static
class
Builder {
// 1 : 存储AlertDialog的各个参数, 例如title, message, icon等.
private
final
AlertController.AlertParams P;
// 属性省略
/**
* Constructor using a context for this builder and the {@link AlertDialog} it creates.
*/
public
Builder(Context context) {
this
(context, resolveDialogTheme(context,
0
));
}
public
Builder(Context context,
int
theme) {
P =
new
AlertController.AlertParams(
new
ContextThemeWrapper(
context, resolveDialogTheme(context, theme)));
mTheme = theme;
}
// Builder的其他代码省略 ......
// 2 : 设置各种参数
public
Builder setTitle(CharSequence title) {
P.mTitle = title;
return
this
;
}
public
Builder setMessage(CharSequence message) {
P.mMessage = message;
return
this
;
}
public
Builder setIcon(
int
iconId) {
P.mIconId = iconId;
return
this
;
}
public
Builder setPositiveButton(CharSequence text,
final
OnClickListener listener) {
P.mPositiveButtonText = text;
P.mPositiveButtonListener = listener;
return
this
;
}
public
Builder setView(View view) {
P.mView = view;
P.mViewSpacingSpecified =
false
;
return
this
;
}
// 3 : 构建AlertDialog, 传递参数
public
AlertDialog create() {
// 调用new AlertDialog构造对象, 并且将参数传递个体AlertDialog
final
AlertDialog dialog =
new
AlertDialog(P.mContext, mTheme,
false
);
// 5 : 将P中的参数应用的dialog中的mAlert对象中
P.apply(dialog.mAlert);
dialog.setCancelable(P.mCancelable);
if
(P.mCancelable) {
dialog.setCanceledOnTouchOutside(
true
);
}
dialog.setOnCancelListener(P.mOnCancelListener);
if
(P.mOnKeyListener !=
null
) {
dialog.setOnKeyListener(P.mOnKeyListener);
}
return
dialog;
}
}
}
联系客服