您的位置:首页 > 其它

Dialog的创建过程

2015-05-29 09:46 429 查看
各位大大我也是初学者,写这些主要是为了对其认识更加清晰,同时也为了以后忘记时可以快速的回忆起。这是我第一次看源码在结合其他大大的思想得到的总结,可能会有很多问题,如果你们发现怎么不对可以告诉我,我很希望能得到你们的评论

首先需要声明的是Dialog不是子窗口,它也是应用窗口。下面就让我们来看看Diglog的创建过程:

1. 通过构造函数创建一个Dialog对象。其构造函数的实际代码如下:

Dialog(Context context, int theme, boolean createContextThemeWrapper) {
if (createContextThemeWrapper) {
if (theme == 0) {
TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(com.android.internal.R.attr.dialogTheme,
outValue, true);
theme = outValue.resourceId;
}
mContext = new ContextThemeWrapper(context, theme);
} else {
mContext = context;
}

mWindowManager = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
Window w = PolicyManager.makeNewWindow(mContext);
mWindow = w;
w.setCallback(this);
w.setWindowManager(mWindowManager, null, null);
w.setGravity(Gravity.CENTER);
mListenersHandler = new ListenersHandler(this);
}
      该构造函数主要做了下面如下工作:

       (1)创建自己的环境变量mContext;

       (2)得到Activity的WindowManager变量;

       (3)创建自己的Window对象,这样就可以独立操作, 因为window是窗口操作的抽象;

       (4)通过w.setCallback(this)设置消息回调接口为Dialog;

       (5)创建回调句柄mListenersHandle,主要为了在内部发送异步消息,所以Dialog只能在UI线程中创建,因为只有UI线程才有消息队列。

        其实这些操作看起来和activity和类似。大家可以回顾下前面的activity的创建过程。

2.上面创建的Dialog对象只是个空格,而且也没有告诉Wms添加一个可以显示的窗口。这些工作就由show()方法来完成吧。下面我们来看看这个高大上的方法实现过程的吧。 

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) {
//1.回调onCreate方法,该方法通过调用setContextView来设置窗口内容视图View
 dispatchOnCreate(null);
}

onStart();
//2.去除上面创建的窗口
 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 ActionBarImpl(this);
}

//3.窗口布局设置
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;
}

try {
//4.将视图绑定一个RootView对象
 mWindowManager.addView(mDecor, l);
mShowing = true;

//5.发送消息,显示Dialog
sendShowMessage();
} finally {
}
}
      以上代码中的五部就是高大上的show方法的实现过程。其实我们发现总个Dialog的创建和显示过程和Activity是很像的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Dialog