popupwindow 的使用
popupwindow 常用api
1. 構(gòu)造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軸的偏移胎挎,正值表示向左沟启,負(fù)值表示向右忆家;yoff表示相對y軸的偏移,正值是向下德迹,負(fù)值是向上芽卿;
showAsDropDown(View anchor, int xoff, int yoff):
//相對于父控件的位置(例如正中央Gravity.CENTER,下方Gravity.BOTTOM等)浦辨,可以設(shè)置偏移或無偏移
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. 創(chuàng)建WindowManager.LayoutParams
|
|
|-preparePopup(p);
|2. 準(zhǔn)備Popup蹬竖,包括創(chuàng)建mBackgroundView,mDecorView
|
|
|-invokePopup(p);
|3. 將decorView 通過mWindowManager.addView(decorView, p);添加window上
#1.createPopupLayoutParams
PopupWindow
|
|-createPopupLayoutParams(IBinder token)
|
|-final WindowManager.LayoutParams p = new WindowManager.LayoutParams();
|創(chuàng)建 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;
|這部分內(nèi)容主要是設(shè)置WindowManager.LayoutParams 的屬性流酬,寬高币厕,flgas,type等
#2.preparePopup
PopupWindow
|
|-preparePopup(p)
|
|-if (mBackground != null) mBackgroundView = createBackgroundView(mContentView);
|-mBackgroundView.setBackground(mBackground);
|-else mBackgroundView = mContentView;
|如果mBackground !=null 會創(chuàng)建一個PopupBackgroundView賦值給mBackgroundView
|否則芽腾,直接將mContentView賦值給mBackgroundView
|
|
|-mDecorView = createDecorView(mBackgroundView);
|創(chuàng)建PopupDecorView旦装,PopupDecorView extends FrameLayout
|重寫dispatchKeyEvent(KeyEvent event),在按返回鍵的時候摊滔,會dismiss方法
|重寫了 onTouchEvent(MotionEvent event) 方法
|在點擊popup 外面的時候阴绢,會執(zhí)行dismiss方法 if(event.getAction() == MotionEvent.ACTION_OUTSIDE) dismiss();
|
|
#3.invokePopup
PopupWindow
|
|-invokePopup(p)
|
|
|-mWindowManager.addView(decorView, p);
|通過WindowManager將PopupDecorView 添加到Window上