在前面的几篇文章中我们分析了Activity与Dialog的加载绘制流程,取消绘制流程,相信大家对Android系统的窗口绘制机制有了一个感性的认识了,这篇文章我们将继续分析一下PopupWindow加载绘制流程。
在分析PopupWindow之前,我们将首先说一下什么是PopupWindow?理解一个类最好的方式就是看一下这个类的定义,这里我们摘要了一下Android系统中PopupWindow的类的说明:
A popup window that can be used to display an arbitrary view. The popup window is a floating container that appears on top of the current
 activity.
一个PopupWindow能够被用于展示任意的View,PopupWindow是一个悬浮的容易展示在当前Activity的上面。
简单来说PopupWindow就是一个悬浮在Activity之上的窗口,可以用展示任意布局文件。
在说明PopupWindow的加载绘制机制之前,我们还是先写一个简单的例子用于说明一下PopupWindow的简单用法。
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 
 | public static View showPopupWindowMenu(Activity mContext, View anchorView, int layoutId) {LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View view = inflater.inflate(layoutId, null);
 popupWindow = new PopupWindow(view, DisplayUtil.dip2px(mContext, 148), WindowManager.LayoutParams.WRAP_CONTENT);
 popupWindow.setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.menu_bg));
 popupWindow.setFocusable(true);
 popupWindow.setOutsideTouchable(true);
 
 int[] location = new int[2];
 anchorView.getLocationOnScreen(location);
 popupWindow.setAnimationStyle(R.style.popwin_anim_style);
 popupWindow.showAtLocation(anchorView, Gravity.NO_GRAVITY,
 location[0] - popupWindow.getWidth() + anchorView.getWidth() - DisplayUtil.dip2px(mContext, 12),
 location[1] + anchorView.getHeight() - DisplayUtil.dip2px(mContext, 10));
 
 popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
 @Override
 public void onDismiss() {
 popupWindow = null;
 }
 });
 return view;
 }
 
 | 
可以看到我们首先通过LayoutInflater对象将布局文件解析到内存中View对象,然后创建了一个PopupWindow对象,可以看到传递了三个参数,一个是View对象,一个是PopupWindow的宽度和高度。
这里就是PopupWindow的初始化流程的开始了,好吧,我们来看一下PopupWindow的构造方法的实现:
| 12
 3
 
 | public PopupWindow(View contentView, int width, int height) {this(contentView, width, height, false);
 }
 
 | 
可以看到这里调用了PopupWindow的重载构造方法,好吧,继续看一下这个重载构造方法的实现逻辑: