popupwindow 的使用
popupwindow 常用api
1. 构造PopupWindow()对象
//方法一:
public PopupWindow (Context context)
//方法二:
public PopupWindow(View contentView)
//方法三:
public PopupWindow(View contentView, int width, int height)
//方法四:
public PopupWindow(View contentView, int width, int height, boolean focusable)
2. 展示PopupWindow()
//相对某个控件的位置(正左下方),无偏移
showAsDropDown(View anchor):
//相对某个控件的位置,有偏移;xoff表示x轴的偏移,正值表示向左,负值表示向右;yoff表示相对y轴的偏移,正值是向下,负值是向上;
showAsDropDown(View anchor, int xoff, int yoff):
//相对于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等),可以设置偏移或无偏移
showAtLocation(View parent, int gravity, int x, int y):
3. 其它Api
public void dismiss()
public void setFocusable(boolean focusable)
public void setTouchable(boolean touchable)
public void setOutsideTouchable(boolean touchable)
public void setBackgroundDrawable(Drawable background)
源码
从showAsDropDown(View anchor)说起
PopupWindow
|
|-showAsDropDown(View anchor, int xoff, int yoff, int gravity)
|
|- final WindowManager.LayoutParams p =createPopupLayoutParams(anchor.getApplicationWindowToken());
|1. 创建WindowManager.LayoutParams
|
|
|-preparePopup(p);
|2. 准备Popup,包括创建mBackgroundView,mDecorView
|
|
|-invokePopup(p);
|3. 将decorView 通过mWindowManager.addView(decorView, p);添加window上
#1.createPopupLayoutParams
PopupWindow
|
|-createPopupLayoutParams(IBinder token)
|
|-final WindowManager.LayoutParams p = new WindowManager.LayoutParams();
|创建 WindowManager.LayoutParams 实例
|
|
|-p.gravity = computeGravity();
|-p.flags = computeFlags(p.flags);
|-p.type = mWindowLayoutType = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
|-p.height = mLastHeight = mHeight;
|- p.width = mLastWidth = mWidth;
|这部分内容主要是设置WindowManager.LayoutParams 的属性,宽高,flgas,type等
#2.preparePopup
PopupWindow
|
|-preparePopup(p)
|
|-if (mBackground != null) mBackgroundView = createBackgroundView(mContentView);
|-mBackgroundView.setBackground(mBackground);
|-else mBackgroundView = mContentView;
|如果mBackground !=null 会创建一个PopupBackgroundView赋值给mBackgroundView
|否则,直接将mContentView赋值给mBackgroundView
|
|
|-mDecorView = createDecorView(mBackgroundView);
|创建PopupDecorView,PopupDecorView extends FrameLayout
|重写dispatchKeyEvent(KeyEvent event),在按返回键的时候,会dismiss方法
|重写了 onTouchEvent(MotionEvent event) 方法
|在点击popup 外面的时候,会执行dismiss方法 if(event.getAction() == MotionEvent.ACTION_OUTSIDE) dismiss();
|
|
#3.invokePopup
PopupWindow
|
|-invokePopup(p)
|
|
|-mWindowManager.addView(decorView, p);
|通过WindowManager将PopupDecorView 添加到Window上