2.4 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上

复制代码

转载于:https://juejin.im/post/5b963612f265da0aff171e3e

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值