Android中所有的视图都是通过Window来呈现的,不管Activity、Dialog还是Toast,他们的视图实际上都是附加在Window上的,Window才是View的直接管理者。
Window和WindowManager
我们先了解一个接口:ViewManager,
public interface ViewManager
{
/**
* Assign the passed LayoutParams to the passed View and add the view to the window.
* Throws {@link android.view.WindowManager.BadTokenException} for certain programming
* errors, such as adding a second view to a window without removing the first view.
*
Throws {@link android.view.WindowManager.InvalidDisplayException} if the window is on a
* secondary {@link Display} and the specified display can't be found
* (see {@link android.app.Presentation}).
* @param view The view to be added to this window.
* @param params The LayoutParams to assign to view.
*/
public void addView(View view, ViewGroup.LayoutParams params);
public void updateViewLayout(View view, ViewGroup.LayoutParams params);
public void removeView(View view);
}
ViewManager约定三个视图的基本操作方式:添加、更新、删除。通常我们使用的WindowManager是对其的继承。
这里先演示一个通过WindowManager添加Window的过程。
button = new Button(this);
button.setText("hello");
mLayoutParams = new WindowManager.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT,0,0,PixelFormat.TRANSPARENT);
mLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL | LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_SHOW_WHEN_LOCKED;
mLayoutParams.gravity = Gravity.LEFT | Gravity.TOP;
mLayoutParams.x = 100;
mLayoutParams.y = 300;
mWindowManager.addView(button, mLayoutParams);
Flags表示Window的属性,这些选项可以控制Window的显示特性,比较常用的有如下几个:
- FLAG_NOT_FOCUSABLE 表示Window不需要获取焦点,也不需要接收各种输入事件,会同时启用FLAG_NOT_TOUCH_MODAL,最终事件会传递给下层具有焦点的Window。(点击事件击穿应该就属于这种情况)
- FLAG_NOT_TOUCH_MODAL 表示系统将当前Window区域以外的单击事件传递给底层的Window,当前Window区域以内的单击事件则自己处理。一般都开启这个标记位,否则其他Window将无法收到单击事件。
- FLAG_SHOW_WHEN_LOCKED 表示让Window显示再锁屏界面上
WindowManager.LayoutParams的type参数用于表示Window所处的层级,通常Window包含这三个层级:
- 系统Window,层级最高,范围2000-2999,type取值有TYPE_SYSTEM_ERROR或者TYPE_SYSTEM_OVERLAY,同时需要声明android.permission.SYSTEM_ALERT_WINDOW
- 子Window,层级范围1000-1999
- 应用Window,层级最低,范围1-99
通过Window,我们可以很快的实现可以拖动的Window效果,通过onTouchListener#onTouch不断更新View的位置即可,如下:
public boolean onTouch(View v, MotionEvent event){
int rawX = v.getRawX();
int rawY = v.getRawY();
switch(event.getAction()){
case MotionEvent.ACTION_MOVE:
mLayoutParams.x = rawX;
mLayoutParams.y = rawY;
mWindowManager.updateViewLayout(button, mLayoutParams);
break;
default: break;
}
return false;
}
Window的创建过程
1. Activity的Window创建过程
Activity实现了Window的Callback接口,因此当Window接收到外界的状态改变时就会回调Activity的方法。几个比较熟悉的,包括onAttachToWindow、onDetachedFromWindow、dispatchTouchEvent、onContentChanged、onWindowFocusChanged等等。
那么Activity视图是怎么附属在Window上的,我们来看setContentView方法的内部实现:
public void setContentView(@LayoutRes int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
那我们再来看Window实现类PhoneWindow#setContentView:
public void setContentView(int layoutResID) {
// Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
// decor, when theme attributes and the like are crystalized. Do not check the feature
// before this happens.
if (mContentParent == null) {
installDecor();// 创建DecorView
} else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
mContentParent.removeAllViews();
}
if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
getContext());
transitionTo(newScene);// 内容的转场动画效果
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);// 将Activity视图添加到DecorView中
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();// 回调Activity实现的Window$Callback#onContentChange方法通知Activity视图已经添加到DecorView的mContentParent中
}
mContentParentExplicitlySet = true;
}
至此,DecorView已创建并初始化,Activity视图也已添加到mContentParent,但是这时DecorView还没有被WindowManager正式添加到Window中。在ActivityThread的handleResumeActivity方法中,首先会调用Activity的onResume方法,接着调用makeVisible(),正是makeVisible方法中真正地完成了添加和显示这两个过程。
void makeVisible() {
if (!mWindowAdded) {
ViewManager wm = getWindowManager();
wm.addView(mDecor, getWindow().getAttributes());
mWindowAdded = true;
}
mDecor.setVisibility(View.VISIBLE);
}
2. Dialog的Window创建过程
整体过程和Activity类似。
1) 创建Window
Dialog(@NonNull Context context, @StyleRes int themeResId, boolean createContextThemeWrapper) {
if (createContextThemeWrapper) {
if (themeResId == 0) {
final TypedValue outValue = new TypedValue();
context.getTheme().resolveAttribute(R.attr.dialogTheme, outValue, true);
themeResId = outValue.resourceId;
}
mContext = new ContextThemeWrapper(context, themeResId);
} else {
mContext = context;
}
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);
}
2)初始化DecorView并往其中添加Dialog视图
public void setContentView(@LayoutRes int layoutResID) {
mWindow.setContentView(layoutResID);
}
3)通过show方法来完成DecorView添加到Window并显示
mWindowManager.addView(mDecor, 1);
mShowing = true;
4)Dialog关闭时会移除DecorView:
mWindowManager.removeViewImmediate(mDecor);