AlertDialog是我们平时使用很多de空间。那么,这个控件是怎么实现的呢?AlertDialog继承自Dialog,实现了很多扩展功能。首先,我们先来看一下AlertDialog类的构造器。
protected AlertDialog(Context context) {
this(context, resolveDialogTheme(context, 0), true);
}
/**
* Construct an AlertDialog that uses an explicit theme. The actual style
* that an AlertDialog uses is a private implementation, however you can
* here supply either the name of an attribute in the theme from which
* to get the dialog's style (such as {@link android.R.attr#alertDialogTheme}
* or one of the constants {@link #THEME_TRADITIONAL},
* {@link #THEME_HOLO_DARK}, or {@link #THEME_HOLO_LIGHT}.
*/
protected AlertDialog(Context context, int theme) {
this(context, theme, true);
}
AlertDialog(Context context, int theme, boolean createThemeContextWrapper) {
super(context, resolveDialogTheme(context, theme), createThemeContextWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
mAlert = new AlertController(getContext(), this, getWindow());
}
protected AlertDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {
super(context, resolveDialogTheme(context, 0));
mWindow.alwaysReadCloseOnTouchAttr();
setCancelable(cancelable);
setOnCancelListener(cancelListener);
mAlert = new AlertController(context, this, getWindow());
}
可以看见,这个类的构造器通过protected修饰。因此,我们不能直接new一个AlertDialog。可以看见,在构造函数中,我们new了一个AlertController类,这个类是用于实现主要逻辑的。那么,我们怎么创建一个AlertDialog类呢?原来,在AlertDialog中有一个静态内部类Builder,我们设置属性等功能都是通过这个类实现的。
public static class Builder {
private final AlertController.AlertParams P;
private int mTheme;
/**
* Constructor using a context for this builder and the {@link AlertDialog} it creates.
*/
public Builder(Context context) {
this(context, resolveDialogTheme(context, 0));
}
/**
* Constructor using a context and theme for this builder and
* the {@link AlertDialo