看一下Builder源码
public static class Builder {private final AlertController.AlertParams P;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)));}//各种set参数方法setTitle()........./** * Creates an {@link AlertDialog} with the arguments supplied to this * builder. * <p> * Calling this method does not display the dialog. If no additional * processing is needed, {@link #show()} may be called instead to both * create and display the dialog. */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;}// 这个show方法是builder对象的,里面封装了create()和show()可以直接调取创建并显示对话框public AlertDialog show() {final AlertDialog dialog = create();dialog.show();return dialog;}}分析源码可以看到内部类
Builder
是用来构建这个对话框的:builder
的时候,会把这个AlertController.AlertParams P;
对象P创建new出来bilder
设置各种参数的时,这些参数都存在了对象P中builder
参数设置完毕后在调用create
方法。final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);P.apply(dialog.mAlert); // mAlert是外部类中的这个方法中会首先调用外部类
AlertDialog
的构造方法,new
出一个外部类对象,然后p.apply()
方法会将P这个对象作为内部类的属性赋值给AlertController
的对象mAlert
。这样就完成了一次的构建。public class AlertDialog extends Dialog implements DialogInterface {// 这个对象用来承接builder内部所设置的参数private AlertController mAlert;//以下几个构造方法决定只能通过内部类builder来构建protected AlertDialog(Context context) {this(context, 0);}protected AlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {this(context, 0);setCancelable(cancelable);setOnCancelListener(cancelListener);}protected AlertDialog(Context context, @StyleRes int themeResId) {this(context, themeResId, true);}AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {super(context, createContextThemeWrapper ? resolveDialogTheme(context, themeResId) : 0,createContextThemeWrapper);mWindow.alwaysReadCloseOnTouchAttr();mAlert = new AlertController(getContext(), this, getWindow());}}总结