Builder模式的定義
将一個複雜對象的 建構 與它的 表示 分離,使得同樣的建構過程可以建立不同的表示。
Builder模式的使用場景
1.相同的方法,不同的執行順序,産生不同的結果。
2.多個部件或零件,都可以裝配到一個對象中,但産生的運作結果又是不同時。
3.産品類非常複雜,或者産品類中的調用順序不同産生了不同的作用,這個時候适合使用構造者模式。
4.當初始化一個對象特别複雜,如參數多,且很多參數都是預設值時。
Android源碼中的Builder模式
public class AlertDialog extends Dialog implements DialogInterface { }
AlertDialog.Builder 通過該Builder來建構複雜的AlertDialog對象。
通過Builder對象組裝Dialog的各個部分,如title、buttons、Message等,将Dialog的構造和表示分離。
private AlertController mAlert; //接收Builder成員變量P中的各個參數
//構造函數
protected AlertDialog(Context context, @StyleRes int themeResId) {
this(context, themeResId, true);
}
//構造函數 AlertDialog
AlertDialog(Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
super(context, createContextThemeWrapper ? resolveDialogTheme(context, themeResId) : 0,
createContextThemeWrapper);
mWindow.alwaysReadCloseOnTouchAttr();
//構造AlertController
mAlert = AlertController.create(getContext(), this, getWindow());
}
//實際調用的是mAlert的setTitle方法
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
/**
* @see Builder#setCustomTitle(View)
*/
//實際上調用的是mAlert的setCustomTitle方法
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
Builder為AlertDialog的内部類
AlertController.AlertParams P 中存儲了AlertDialig的各個參數。
//Builder為AlertDialog的内部類
public static class Builder {
... ...
}
//儲存AlertDialog的各個參數,如title、message、icon等
private final AlertController.AlertParams P;
public Builder(Context context) {
this(context, resolveDialogTheme(context, ResourceId.ID_NULL));
}
public Builder(Context context, int themeResId) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, themeResId)));
}
下述代碼中,Builder類可以設定AlertDialog中的title、message、button等參數,這些參數都存儲在類型為AlertController.AlertParams的成員變量P中,AlertController.AlertParams包含了與AlertDialog視圖中對應的成員變量。在調用Builder類的create函數時會建立AlertDialog,并且将Builder成員變量P中儲存的參數應用到AlertDialog的mAlert對象中,即P.apply(dialog.mAlert)代碼段。
//設定各種參數
/**
* Set the title displayed in the {@link Dialog}.
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
/**
* Set the message to display.
*
* @return This Builder object to allow for chaining of calls to set methods
*/
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
public Builder setView(View view) {
P.mView = view;
P.mViewLayoutResId = 0;
P.mViewSpacingSpecified = false;
return this;
}
//構造AlertDialog,傳遞參數
public AlertDialog create() {
// Context has already been wrapped with the appropriate theme.
//調用new AlertDialog構造對象,并且将參數傳遞給個體AlertDialog。
final AlertDialog dialog = new AlertDialog(P.mContext, 0, false);
//将P中的參數應用到 dialog 中的mAlert對象中。
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;
}
上述代碼中,Builder類可以設定AlertDialog中的title、message、button等參數,這些參數都存儲在類型為AlertController.AlertParams的成員變量P中,AlertController.AlertParams包含了與AlertDialog視圖中對應的成員變量。在調用Builder類的create函數時會建立AlertDialog,并且将Builder成員變量P中儲存的參數應用到AlertDialog的mAlert對象中,即P.apply(dialog.mAlert)代碼段。
#AlertController
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 (mForceInverseBackground) {
dialog.setInverseBackgroundForced(true);
}
// For a list, the client can either supply an array of items or an
// adapter or a cursor
if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
createListView(dialog);
}
if (mView != null) {
if (mViewSpacingSpecified) {
dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
} else {
dialog.setView(mView);
}
} else if (mViewLayoutResId != 0) {
dialog.setView(mViewLayoutResId);
}
/*
dialog.setCancelable(mCancelable);
dialog.setOnCancelListener(mOnCancelListener);
if (mOnKeyListener != null) {
dialog.setOnKeyListener(mOnKeyListener);
}
*/
}
AlertParams是AlertController 的靜态内部類
#AlertParams
在apply函數中,隻是将AlertParams參數設定到AlertController中,例如将标題設定到Dialog對應的标題視圖中等。當我們擷取到AlertDialog對象後,通過show函數就可以顯示這個對話框。
public static class AlertParams {
... ...
}
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 (mForceInverseBackground) {
dialog.setInverseBackgroundForced(true);
}
// For a list, the client can either supply an array of items or an
// adapter or a cursor
//如果設定了mItems時,則表示是單選或者多選清單,此時建立的是一個ListView。
if ((mItems != null) || (mCursor != null) || (mAdapter != null)) {
createListView(dialog);
}
//将mView設定給Dialog
if (mView != null) {
if (mViewSpacingSpecified) {
dialog.setView(mView, mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight,
mViewSpacingBottom);
} else {
dialog.setView(mView);
}
} else if (mViewLayoutResId != 0) {
dialog.setView(mViewLayoutResId);
}
/*
dialog.setCancelable(mCancelable);
dialog.setOnCancelListener(mOnCancelListener);
if (mOnKeyListener != null) {
dialog.setOnKeyListener(mOnKeyListener);
}
*/
}
在apply函數中,隻是将AlertParams參數設定到AlertController中,例如将标題設定到Dialog對應的标題視圖中等。當我們擷取到AlertDialog對象後,通過show函數就可以顯示這個對話框。
/**
* Creates an {@link AlertDialog} with the arguments supplied to this
* builder and immediately displays the dialog.
* <p>
* Calling this method is functionally identical to:
* <pre>
* AlertDialog dialog = builder.create();
* dialog.show();
* </pre>
*/
#AlertDialog.Builder
public AlertDialog show() {
final AlertDialog dialog = create();
dialog.show();
return dialog;
}
Dialog的show函數如下:
public class AlertDialog extends Dialog implements DialogInterface {
... ...
}
/**
* Start the dialog and display it on screen. The window is placed in the
* application layer and opaque. Note that you should not override this
* method to do initialization when the dialog is shown, instead implement
* that in {@link #onStart}.
*/
#Dialog
public void show() {
//已經是顯示狀态,則return
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;
//1.onCreate調用
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);
}
onStart();
//擷取DecorView
mDecor = mWindow.getDecorView();
if (mActionBar == null && mWindow.hasFeature(Window.FEATURE_ACTION_BAR)) {
final ApplicationInfo info = mContext.getApplicationInfo();
mWindow.setDefaultIcon(info.icon);
mWindow.setDefaultLogo(info.logo);
mActionBar = new WindowDecorActionBar(this);
}
//擷取布局參數
WindowManager.LayoutParams l = mWindow.getAttributes();
if ((l.softInputMode
& WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION) == 0) {
WindowManager.LayoutParams nl = new WindowManager.LayoutParams();
nl.copyFrom(l);
nl.softInputMode |=
WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION;
l = nl;
}
//将mDecor添加到WindowManager中
mWindowManager.addView(mDecor, l);
mShowing = true;
//發送一個顯示Dialog的消息
sendShowMessage();
}
在show函數中主要做如下幾件事:
1.通過dispatchOnCreate函數來調用AlertDialog的onCreate函數。
2.然後調用AlertDialog的onStart函數。
3.最後将Dialog的DecorView添加到WindowManager中。
這是一系列典型的生命周期函數。按照慣例,AlertDialog的内容視圖建構應該在onCreate函數中。
AlertDialog的onCreate函數:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 調用了AlertController的installContent方法
mAlert.installContent();
}
在onCreate函數中主要調用了AlertController的installContent方法,Dialog中的onCreate函數隻是一個空實作。AlertDialog的内容視圖必然在installContent函數中。
#AlertController
public void installContent() {
//設定視窗沒有title
mWindow.requestFeature(Window.FEATURE_NO_TITLE);
int contentView = selectContentView();
//設定視窗的内容視圖布局
mWindow.setContentView(contentView);
//初始化AlertDialog的其他子視圖的内容
setupView();
}
installContent函數的代碼很少,但極為重要,它調用了Window對象的setContentView,這個setContentView就與Activity中的一樣,實際上Activity最終也是調用Window對象的setContentView函數。這裡是設定AlertDialog的内容布局,這個布局就是mAlertDialogLayout字段值。這個值在AlertController的構造函數中初始化。
#AlertController
protected AlertController(Context context, DialogInterface di, Window window) {
mContext = context;
mDialogInterface = di;
mWindow = window;
mHandler = new ButtonHandler(di);
final TypedArray a = context.obtainStyledAttributes(null,
R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);
// modify begin by sunliang for AlertDialog 20170721
useGomeTheme = a.getBoolean(R.styleable.AlertDialog_useGomeTheme, false);
if(useGomeTheme){
mAlertDialogLayout = a.getResourceId(
com.gome.R.styleable.AlertDialog_layout, com.gome.R.layout.gome_alert_dialog);
} else {
//AlertDialog的布局id,也就是alert_dialog.xml布局
mAlertDialogLayout = a.getResourceId(
R.styleable.AlertDialog_layout, R.layout.alert_dialog);
}
if(useGomeTheme) {
mButtonPanelSideLayout = a.getResourceId(
com.gome.R.styleable.AlertDialog_buttonPanelSideLayout, 0);
} else {
mButtonPanelSideLayout = a.getResourceId(
R.styleable.AlertDialog_buttonPanelSideLayout, 0);
}
if(useGomeTheme) {
mListLayout = R.layout.select_dialog_gome;
} else {
mListLayout = a.getResourceId(
R.styleable.AlertDialog_listLayout, R.layout.select_dialog);
}
if(useGomeTheme) {
mMultiChoiceItemLayout = a.getResourceId(
com.gome.R.styleable.AlertDialog_multiChoiceItemLayout,
com.gome.R.layout.gome_select_dialog_multichoice);
} else {
mMultiChoiceItemLayout = a.getResourceId(
R.styleable.AlertDialog_multiChoiceItemLayout,
R.layout.select_dialog_multichoice);
}
if(useGomeTheme) {
mSingleChoiceItemLayout = a.getResourceId(
com.gome.R.styleable.AlertDialog_singleChoiceItemLayout,
com.gome.R.layout.gome_select_dialog_singlechoice);
} else {
mSingleChoiceItemLayout = a.getResourceId(
R.styleable.AlertDialog_singleChoiceItemLayout,
com.gome.internal.R.layout.gome_select_singlechoice);
}
if(useGomeTheme) {
mListItemLayout = a.getResourceId(
com.gome.R.styleable.AlertDialog_listItemLayout,
com.gome.R.layout.gome_select_dialog_item);
} else {
mListItemLayout = a.getResourceId(
R.styleable.AlertDialog_listItemLayout,
R.layout.select_dialog_item);
}
//modify end by sunliang for AlertDialog 20170721
mShowTitle = a.getBoolean(R.styleable.AlertDialog_showTitle, true);
a.recycle();
/* We use a custom title so never request a window title */
//window.requestFeature(Window.FEATURE_NO_TITLE);
}
當通過Builder對象的setTitle、setMessage等方法設定具體内容時,就是将這些内容填充到對應的視圖中。而AlertDialog也允許你通過setView傳入内容視圖,這個内容視圖就是替換掉藍色區域。AlertDialog預留了一個costomPanel區域用來顯示使用者自定義的内容視圖。
private void setupView() {
//modify begin by sunliang for AlertDialog 20170721
// final View parentPanel = mWindow.findViewById(R.id.parentPanel);
// final View defaultTopPanel = parentPanel.findViewById(R.id.topPanel);
// final View defaultContentPanel = parentPanel.findViewById(R.id.contentPanel);
// final View defaultButtonPanel = parentPanel.findViewById(R.id.buttonPanel);
View parentPanel;
//擷取并初始化title區域
if(useGomeTheme) {
parentPanel = mWindow.findViewById(com.gome.R.id.parentPanel);
} else {
parentPanel = mWindow.findViewById(R.id.parentPanel);
}
View defaultTopPanel;
if(useGomeTheme) {
defaultTopPanel = parentPanel.findViewById(com.gome.R.id.topPanel);
} else {
defaultTopPanel = parentPanel.findViewById(R.id.topPanel);
}
View defaultContentPanel;
if(useGomeTheme) {
defaultContentPanel = parentPanel.findViewById(com.gome.R.id.contentPanel);
} else {
defaultContentPanel = parentPanel.findViewById(R.id.contentPanel);
}
View defaultButtonPanel;
// 擷取并初始化内容區域
if(useGomeTheme) {
defaultButtonPanel = parentPanel.findViewById(com.gome.R.id.buttonPanel);
} else {
defaultButtonPanel = parentPanel.findViewById(R.id.buttonPanel);
}
// Install custom content before setting up the title or buttons so
// that we can handle panel overrides.
// final ViewGroup customPanel = (ViewGroup) parentPanel.findViewById(R.id.customPanel);
// setupCustomContent(customPanel);
//
// final View customTopPanel = customPanel.findViewById(R.id.topPanel);
// final View customContentPanel = customPanel.findViewById(R.id.contentPanel);
// final View customButtonPanel = customPanel.findViewById(R.id.buttonPanel);
//
// // Resolve the correct panels and remove the defaults, if needed.
// final ViewGroup topPanel = resolvePanel(customTopPanel, defaultTopPanel);
// final ViewGroup contentPanel = resolvePanel(customContentPanel, defaultContentPanel);
// final ViewGroup buttonPanel = resolvePanel(customButtonPanel, defaultButtonPanel);
ViewGroup customPanel;
if(useGomeTheme) {
customPanel = (ViewGroup) parentPanel.findViewById(com.gome.R.id.customPanel);
} else {
customPanel = (ViewGroup) parentPanel.findViewById(R.id.customPanel);
}
setupCustomContent(customPanel);
View customTopPanel;
if(useGomeTheme) {
customTopPanel = customPanel.findViewById(com.gome.R.id.topPanel);
} else {
customTopPanel = customPanel.findViewById(R.id.topPanel);
}
View customContentPanel;
if(useGomeTheme) {
customContentPanel = customPanel.findViewById(com.gome.R.id.contentPanel);
} else {
customContentPanel = customPanel.findViewById(R.id.contentPanel);
}
View customButtonPanel;
if(useGomeTheme) {
customButtonPanel = customPanel.findViewById(com.gome.R.id.buttonPanel);
} else {
customButtonPanel = customPanel.findViewById(R.id.buttonPanel);
}
//modify end by sunliang for AlertDialog 20170721
// Resolve the correct panels and remove the defaults, if needed.
final ViewGroup topPanel = resolvePanel(customTopPanel, defaultTopPanel);
final ViewGroup contentPanel = resolvePanel(customContentPanel, defaultContentPanel);
final ViewGroup buttonPanel = resolvePanel(customButtonPanel, defaultButtonPanel);
setupContent(contentPanel);
//初始化按鈕
setupButtons(buttonPanel);
setupTitle(topPanel);
final boolean hasCustomPanel = customPanel != null
&& customPanel.getVisibility() != View.GONE;
final boolean hasTopPanel = topPanel != null
&& topPanel.getVisibility() != View.GONE;
final boolean hasButtonPanel = buttonPanel != null
&& buttonPanel.getVisibility() != View.GONE;
// Only display the text spacer if we don't have buttons.
if (!hasButtonPanel) {
if (contentPanel != null) {
final View spacer = contentPanel.findViewById(R.id.textSpacerNoButtons);
if (spacer != null) {
spacer.setVisibility(View.VISIBLE);
}
}
mWindow.setCloseOnTouchOutsideIfNotSet(true);
}
if (hasTopPanel) {
// Only clip scrolling content to padding if we have a title.
if (mScrollView != null) {
mScrollView.setClipToPadding(true);
}
// Only show the divider if we have a title.
View divider = null;
if (mMessage != null || mListView != null || hasCustomPanel) {
if (!hasCustomPanel) {
divider = topPanel.findViewById(R.id.titleDividerNoCustom);
}
if (divider == null) {
divider = topPanel.findViewById(R.id.titleDivider);
}
} else {
divider = topPanel.findViewById(R.id.titleDividerTop);
}
if (divider != null) {
divider.setVisibility(View.VISIBLE);
}
} else {
if (contentPanel != null) {
final View spacer = contentPanel.findViewById(R.id.textSpacerNoTitle);
if (spacer != null) {
spacer.setVisibility(View.VISIBLE);
}
}
}
if (mListView instanceof RecycleListView) {
((RecycleListView) mListView).setHasDecor(hasTopPanel, hasButtonPanel);
}
// Update scroll indicators as needed.
if (!hasCustomPanel) {
final View content = mListView != null ? mListView : mScrollView;
if (content != null) {
final int indicators = (hasTopPanel ? View.SCROLL_INDICATOR_TOP : 0)
| (hasButtonPanel ? View.SCROLL_INDICATOR_BOTTOM : 0);
content.setScrollIndicators(indicators,
View.SCROLL_INDICATOR_TOP | View.SCROLL_INDICATOR_BOTTOM);
}
}
final TypedArray a = mContext.obtainStyledAttributes(
null, R.styleable.AlertDialog, R.attr.alertDialogStyle, 0);
//設定背景
setBackground(a, topPanel, contentPanel, customPanel, buttonPanel,
hasTopPanel, hasCustomPanel, hasButtonPanel);
a.recycle();
}
}
private void setupCustomContent(ViewGroup customPanel) {
final View customView;
如果使用者設定了内容視圖,那麼将它顯示在customPanel的custom布局裡面
if (mView != null) {
customView = mView;
} else if (mViewLayoutResId != 0) {
final LayoutInflater inflater = LayoutInflater.from(mContext);
customView = inflater.inflate(mViewLayoutResId, customPanel, false);
} else {
customView = null;
}
final boolean hasCustomView = customView != null;
if (!hasCustomView || !canTextInput(customView)) {
mWindow.setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}
if (hasCustomView) {
//modify begin by sunliang for AlertDialog 20170721
// final FrameLayout custom = (FrameLayout) mWindow.findViewById(R.id.custom);
FrameLayout custom;
if(useGomeTheme) {
custom = (FrameLayout) mWindow.findViewById(com.gome.R.id.custom);
} else {
custom = (FrameLayout) mWindow.findViewById(R.id.custom);
}
//modify end by sunliang for AlertDialog 20170721
//顯示使用者設定的視圖
custom.addView(customView, new LayoutParams(MATCH_PARENT, MATCH_PARENT));
if (mViewSpacingSpecified) {
custom.setPadding(
mViewSpacingLeft, mViewSpacingTop, mViewSpacingRight, mViewSpacingBottom);
}
if (mListView != null) {
((LinearLayout.LayoutParams) customPanel.getLayoutParams()).weight = 0;
}
} else {
customPanel.setVisibility(View.GONE);
}
}
setupView顧名思義就是初始化AlertDialog布局的各個部分,在該函數調用之後,整個Dialog的視圖内容全部設定完畢。這些各區域的視圖都屬于mAlertDialogLayout布局中的子元素,Window對象又關聯了mAlertDialogLayout的整個布局樹,調用完setupView之後整個視圖樹的資料填充完畢,當使用者調用show函數時,WindowManager将會将Window對象的DecorView添加到使用者視窗上。
注意AlertDialog的setView方法和setContentView方法:
setView方法需要在show方法之前調用。setView是AlertDialog的方法,在AlertDialog中調用AlertController中的setView。而在AlertController中這個setView則是指的CustomView的部分而不是整個窗體。
注意AlertDialog的setView方法和setContentView方法:
setView方法需要在show方法之前調用。setView是AlertDialog的方法,在AlertDialog中調用AlertController中的setView。而在AlertController中這個setView則是指的CustomView的部分而不是整個窗體。
setContentView實際調用的是PhonWindow的setContentView方法,其設定的是整個視窗的布局。
參考《android源碼設計模式》