轉(zhuǎn)載請注明文章出處LooperJing!
上一篇分析了一下Activity的Window創(chuàng)建過程和Window與Activity是如何關(guān)聯(lián)到一起的,通過上一篇,我們對Window有了基本的認(rèn)識。這一篇分享一下我對Dialog加載繪制流程的理解。
首先創(chuàng)建一個Dialog,回顧下創(chuàng)建Dialog的流程。
public class MainActivity extends Activity {
AlertDialog alertDialog=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.mipmap.ic_launcher);
builder.setMessage("Message部分");
builder.setTitle("Title部分");
builder.setView(R.layout.activity_main);
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog = builder.create();
alertDialog.show();
}
}
運行效果如下,截圖中hello world是main布局里面的。

我們看一下Dialog的部分代碼
public class AlertDialog extends AppCompatDialog implements DialogInterface {
final AlertController mAlert;
static final int LAYOUT_HINT_NONE = 0;
static final int LAYOUT_HINT_SIDE = 1;
protected AlertDialog(@NonNull Context context) {
this(context, 0);
}
/**
*構(gòu)造函數(shù),可以指定主題,比如 R.attr#alertDialogTheme
*/
protected AlertDialog(@NonNull Context context, @StyleRes int themeResId) {
super(context, resolveDialogTheme(context, themeResId));
mAlert = new AlertController(getContext(), this, getWindow());
}
/**
*構(gòu)造函數(shù),點擊外部是否可取消,取消時候的回調(diào)
*/
protected AlertDialog(@NonNull Context context, boolean cancelable,
@Nullable OnCancelListener cancelListener) {
this(context, 0);
setCancelable(cancelable);
setOnCancelListener(cancelListener);
}
/**
獲取對話框中的按鈕,比如可以獲取BUTTON_POSITIVE
*/
public Button getButton(int whichButton) {
return mAlert.getButton(whichButton);
}
//設(shè)置標(biāo)題,內(nèi)部調(diào)用了 mAlert.setTitle(title)
@Override
public void setTitle(CharSequence title) {
super.setTitle(title);
mAlert.setTitle(title);
}
/**
* 標(biāo)題也可能是一個View,此時設(shè)置標(biāo)題用這個方法
*/
public void setCustomTitle(View customTitleView) {
mAlert.setCustomTitle(customTitleView);
}
public void setMessage(CharSequence message) {
mAlert.setMessage(message);
}
.......
public static class Builder {
private final AlertController.AlertParams P;
private final int mTheme;
//構(gòu)造函數(shù)
public Builder(@NonNull Context context) {
this(context, resolveDialogTheme(context, 0));
}
//構(gòu)造函數(shù)
public Builder(@NonNull Context context, @StyleRes int themeResId) {
P = new AlertController.AlertParams(new ContextThemeWrapper(
context, resolveDialogTheme(context, themeResId)));
mTheme = themeResId;
}
@NonNull
public Context getContext() {
return P.mContext;
}
public Builder setTitle(@StringRes int titleId) {
P.mTitle = P.mContext.getText(titleId);
return this;
}
public Builder setTitle(CharSequence title) {
P.mTitle = title;
return this;
}
public Builder setCustomTitle(View customTitleView) {
P.mCustomTitleView = customTitleView;
return this;
}
public Builder setMessage(@StringRes int messageId) {
P.mMessage = P.mContext.getText(messageId);
return this;
}
public Builder setMessage(CharSequence message) {
P.mMessage = message;
return this;
}
.......
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
//Dialog的參數(shù)其實保存在P這個類里面
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;
}
public AlertDialog show() {
final AlertDialog dialog = create();
dialog.show();
return dialog;
}
}
}
從代碼中可以看到,我們創(chuàng)建的Dialog是什么樣式,可以通過Builder的set系列方法指定,是當(dāng)我們調(diào)用Builder的set系列方法的時候,會將我們傳遞的參數(shù)保存在P中,這個P是什么呢?在Builder有一個成員
private final AlertController.AlertParams P;
P是AlertController的內(nèi)部類AlertParams類型的變量。AlertParams中包含了與AlertDialog視圖中對應(yīng)的成員變量。調(diào)用Builder的set系列方法之后,我們傳遞的參數(shù)就保存在P中了。P存在之后,我們就可以創(chuàng)建對話框了。這個就好像,我們要建造房子,得先有設(shè)計圖紙,圖紙決定了房子的樣子。
public AlertDialog create() {
final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
P.apply(dialog.mAlert);
}
用new的方式創(chuàng)建一個AlertDialog,AlertDialog的構(gòu)造函數(shù)中調(diào)用了super,AlertDialog繼承Dialog,看一下Dialog的構(gòu)造函數(shù)。
Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
....
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
final Window w = new PhoneWindow(mContext);
mWindow = w;
w.setCallback(this);
w.setOnWindowDismissedCallback(this);
w.setWindowManager(mWindowManager, null, null);
w.setGravity(Gravity.CENTER);
mListenersHandler = new ListenersHandler(this);
}
可以發(fā)現(xiàn)直接new了一個PhoneWindow賦值給mWindow,并且設(shè)置了callback回調(diào),當(dāng)窗口狀態(tài)發(fā)生變化的時候,就會回調(diào)Dialog中的callback實現(xiàn)。這個和Activity的一模一樣,之前已經(jīng)分析過了。當(dāng)你new AlertDialog()之后,到此,Dialog所需要的Window就有了。接下來,就要分析,Dialogd的視圖怎么與Window做關(guān)聯(lián)了,繼續(xù)往下面走。
在AlertDialog創(chuàng)建之后,就調(diào)用 P.apply(dialog.mAlert),將P中的參數(shù)賦值給dialog的mAlert,mAlert是AlertController類型。我們看一下apply函數(shù)。
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 ((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);
}
}
代碼很簡單,就純粹做一件事,把P中的參數(shù)賦值給dialog的mAlert中對應(yīng)的參數(shù),比如標(biāo)題,按鈕等等。這些都沒有什么,下面干貨來了。繼續(xù)看Dialog的show方法,記住,我們現(xiàn)在的任務(wù)是,分析Dialog視圖是怎么與Window做關(guān)聯(lián)的!。
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);
}
onStart();
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;
}
mWindowManager.addView(mDecor, l);
mShowing = true;
sendShowMessage();
}
看下面,當(dāng)mCreated為假的時候,調(diào)用dispatchOnCreate,最終是回調(diào)了Dialog的onCreate方法。
if (!mCreated) {
dispatchOnCreate(null);
}
void dispatchOnCreate(Bundle savedInstanceState) {
if (!mCreated) {
onCreate(savedInstanceState);
mCreated = true;
}
}
protected void onCreate(Bundle savedInstanceState) {
}
Dialog里面的onCreate是個空實現(xiàn),我們要看看AlertDialog的onCreate方法的里面的東西。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mAlert.installContent();
}
調(diào)用 mAlert.installContent()方法,上面說了mAlert是AlertController類型,AlertController中有Dialog所需要的樣式參數(shù)。
public void installContent() {
final int contentView = selectContentView();
mDialog.setContentView(contentView);
setupView();
}
有木有?。。〗K于發(fā)現(xiàn)了setContentView方法,先通過selectContentView布局文件的ID,然后調(diào)用Window的setContentView方法,加載指定的文件到DecorView的Content部分,并且回調(diào)onContentChanged方法通知Dialog。
@Override
public void setContentView(int resId) {
ensureSubDecor();
ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
LayoutInflater.from(mContext).inflate(resId, contentParent);
mOriginalWindowCallback.onContentChanged();
}
setContentView執(zhí)行之后,調(diào)用了setupView方法和setupDector方法,這兩個方法的主要作用就是初始化布局文件中的組件和Window對象中的mDector成員變量?,F(xiàn)在回到我們的show方法,在執(zhí)行了dispatchOnCreate方法之后我們又調(diào)用了onStart方法。在看show方法里面,會調(diào)用下面三行代碼。
mDecor = mWindow.getDecorView();
WindowManager.LayoutParams l = mWindow.getAttributes();
mWindowManager.addView(mDecor, l);
最終會通過WindowManager將DecorView添加到Window之中,OK到這里整個Dialog的界面就會被繪制出來了。
總結(jié)一下:AlertDialog和Activity一樣,內(nèi)部有一個Window,我們構(gòu)造AlertDialog.Builder,通過Builder設(shè)置Dialog各種屬性,,這些參數(shù)會被放在一個名為P(AlertController類型)的變量中,在調(diào)用AlertDialog.Builder.create方法的時候,內(nèi)部首先會new一個 AlertDialog,AlertDialog的父類Dialog的構(gòu)造函數(shù)中會new一個PhoneWindow賦值給AlertDialog中的Window,并且為它設(shè)置了回調(diào)。AlertDialog創(chuàng)建之后執(zhí)行apply方法,將P中的參數(shù)設(shè)置賦值給Dialog,后我們調(diào)用Dialog.show方法展示窗口,內(nèi)部調(diào)用dispatchOnCreate,最終會走到setContentView,到此Dialog的Window和Dialog視圖關(guān)聯(lián)到了一起,最后執(zhí)行mWindowManager.addView方法,通過WindowManager將DecorView添加到Window之中,此時Dialog顯示在了我們面前。
Please accept mybest wishes for your happiness and success!