Android源码解析Window系列第(二)篇---Dialog加载绘制流程

转载请注明文章出处LooperJing

上一篇分析了一下Activity的Window创建过程和Window与Activity是如何关联到一起的,通过上一篇,我们对Window有了基本的认识。这一篇分享一下我对Dialog加载绘制流程的理解。

首先创建一个Dialog,回顾下创建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);
    }

    /**
     *构造函数,可以指定主题,比如 R.attr#alertDialogTheme
     */
    protected AlertDialog(@NonNull Context context, @StyleRes int themeResId) {
        super(context, resolveDialogTheme(context, themeResId));
        mAlert = new AlertController(getContext(), this, getWindow());
    }

    /**
     *构造函数,点击外部是否可取消,取消时候的回调
     */
    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);
    }

    //设置标题,内部调用了  mAlert.setTitle(title)
    @Override
    public void setTitle(CharSequence title) {
        super.setTitle(title);
        mAlert.setTitle(title);
    }

    /**
     * 标题也可能是一个View,此时设置标题用这个方法
     */
    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;

         //构造函数
        public Builder(@NonNull Context context) {
            this(context, resolveDialogTheme(context, 0));
        }

         //构造函数
        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的参数其实保存在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;
        }
    }
}

从代码中可以看到,我们创建的Dialog是什么样式,可以通过Builder的set系列方法指定,是当我们调用Builder的set系列方法的时候,会将我们传递的参数保存在P中,这个P是什么呢?在Builder有一个成员

private final AlertController.AlertParams P;

P是AlertController的内部类AlertParams类型的变量。AlertParams中包含了与AlertDialog视图中对应的成员变量。调用Builder的set系列方法之后,我们传递的参数就保存在P中了。P存在之后,我们就可以创建对话框了。这个就好像,我们要建造房子,得先有设计图纸,图纸决定了房子的样子。

public AlertDialog create() {
    final AlertDialog dialog = new AlertDialog(P.mContext, mTheme);
    P.apply(dialog.mAlert);
}

用new的方式创建一个AlertDialog,AlertDialog的构造函数中调用了super,AlertDialog继承Dialog,看一下Dialog的构造函数。

 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);
    }

可以发现直接new了一个PhoneWindow赋值给mWindow,并且设置了callback回调,当窗口状态发生变化的时候,就会回调Dialog中的callback实现。这个和Activity的一模一样,之前已经分析过了。当你new AlertDialog()之后,到此,Dialog所需要的Window就有了。接下来,就要分析,Dialogd的视图怎么与Window做关联了,继续往下面走。

在AlertDialog创建之后,就调用 P.apply(dialog.mAlert),将P中的参数赋值给dialog的mAlert,mAlert是AlertController类型。我们看一下apply函数。

 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中的参数赋值给dialog的mAlert中对应的参数,比如标题,按钮等等。这些都没有什么,下面干货来了。继续看Dialog的show方法,记住,我们现在的任务是,分析Dialog视图是怎么与Window做关联的!

    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();
    }

看下面,当mCreated为假的时候,调用dispatchOnCreate,最终是回调了Dialog的onCreate方法。

  if (!mCreated) {
      dispatchOnCreate(null);
   }
 void dispatchOnCreate(Bundle savedInstanceState) {
        if (!mCreated) {
            onCreate(savedInstanceState);
            mCreated = true;
        }
    }
protected void onCreate(Bundle savedInstanceState) {
}

Dialog里面的onCreate是个空实现,我们要看看AlertDialog的onCreate方法的里面的东西。

   @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mAlert.installContent();
    }

调用 mAlert.installContent()方法,上面说了mAlert是AlertController类型,AlertController中有Dialog所需要的样式参数。

  public void installContent() {
        final int contentView = selectContentView();
        mDialog.setContentView(contentView);
        setupView();
    }

有木有!!!终于发现了setContentView方法,先通过selectContentView布局文件的ID,然后调用Window的setContentView方法,加载指定的文件到DecorView的Content部分,并且回调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执行之后,调用了setupView方法和setupDector方法,这两个方法的主要作用就是初始化布局文件中的组件和Window对象中的mDector成员变量。现在回到我们的show方法,在执行了dispatchOnCreate方法之后我们又调用了onStart方法。在看show方法里面,会调用下面三行代码。

    mDecor = mWindow.getDecorView();

    WindowManager.LayoutParams l = mWindow.getAttributes();

   mWindowManager.addView(mDecor, l);

最终会通过WindowManager将DecorView添加到Window之中,OK到这里整个Dialog的界面就会被绘制出来了。
总结一下:AlertDialog和Activity一样,内部有一个Window,我们构造AlertDialog.Builder,通过Builder设置Dialog各种属性,,这些参数会被放在一个名为P(AlertController类型)的变量中,在调用AlertDialog.Builder.create方法的时候,内部首先会new一个 AlertDialog,AlertDialog的父类Dialog的构造函数中会new一个PhoneWindow赋值给AlertDialog中的Window,并且为它设置了回调。AlertDialog创建之后执行apply方法,将P中的参数设置赋值给Dialog,后我们调用Dialog.show方法展示窗口,内部调用dispatchOnCreate,最终会走到setContentView,到此Dialog的Window和Dialog视图关联到了一起,最后执行mWindowManager.addView方法,通过WindowManager将DecorView添加到Window之中,此时Dialog显示在了我们面前。

Please accept mybest wishes for your happiness and success!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 151,688评论 1 330
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 64,559评论 1 273
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 101,749评论 0 226
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 42,581评论 0 191
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 50,741评论 3 271
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 39,684评论 1 192
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,122评论 2 292
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 29,847评论 0 182
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 33,441评论 0 228
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 29,939评论 2 232
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 31,333评论 1 242
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 27,783评论 2 236
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,275评论 3 220
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 25,830评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,444评论 0 180
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 34,553评论 2 249
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 34,618评论 2 249

推荐阅读更多精彩内容