Android 开发中弹框随处可见,现将自己做过的项目中的PopupWindow,做出一个系统的总结。从以下方面开始总结:
第一篇使用篇:
- PopupWindow 的使用.
- 示例演示
- 与Dialog的区别.
第二篇源码篇:
PopupWindow的原理解析与源码剖析.
有对Dialog的使用不清楚的,请查看我的另外一篇关于Dialog文章:
http://blog.csdn.net/dachaoxuexi/article/details/51274379
PopupWindow的使用
构造方法
- public PopupWindow(Context context) {
this(context, null);
} - public PopupWindow(Context context, AttributeSet attrs) {
this(context, attrs, com.android.internal.R.attr.popupWindowStyle);
} - public PopupWindow(Context context, AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
} - public PopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
…
} - public PopupWindow() {
this(null, 0, 0);
} - public PopupWindow(View contentView) {
this(contentView, 0, 0);
} - public PopupWindow(int width, int height) {
this(null, width, height);
} - public PopupWindow(View contentView, int width, int height) {
this(contentView, width, height, false);
}
9.public PopupWindow(View contentView, int width, int height, boolean focusable) {}
- public PopupWindow(Context context) {
从构造方法中,可以看出构造最终调用的是public PopupWindow(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {},与public PopupWindow(View contentView, int width, int height, boolean focusable) {};分别是自定义与直接设置参数两种情况,无论是哪种情况,想要弹框,都必须具备的条件是:
- contentView 要显示的布局
- width 布局的宽度
- height 布局的高度
注意:因为PopupWindow没有默认布局,所以必须设置contentView .
- 常用方法
常用方法一显示弹框:
方法一:
public void showAtLocation(View parent, int gravity, int x, int y) {
showAtLocation(parent.getWindowToken(), gravity, x, y);
}
方法二:
public void showAtLocation(IBinder token, int gravity, int x, int y) {...}
方法三:
public void showAsDropDown(View anchor) {
showAsDropDown(anchor, 0, 0);
}
方法四:
public void showAsDropDown(View anchor, int xoff, int yoff) {
showAsDropDown(anchor, xoff, yoff, DEFAULT_ANCHORED_GRAVITY);
}
方法五:
public void showAsDropDown(View anchor, int xoff, int yoff, int gravity) {...}
可以看出,显示方法可以归结为两种方式:
第一种,showAtLocation(),相对于父控件parent的位置,可以通过gravity来设置,也可以设置偏移量,通过设置x,y来设置在X,Y轴上的偏移量;亲测parent这个view可以是当前view的随意一个view,不会挂掉.
第二种,showAsDropDown(),相对anchor的位置,从正左下方开始计算,偏移量可以通过int xoff, int yoff设置,gravity是相对于anchor的gravity.
常用方法二设置contentView:
通过构造方法或者setContentView(View contentView)来设置contentView.
常用方法三设置宽高:
通过构造方法或者setWidth(int width)和setHeight(int height)来设置.
常用方法四设置focusable:
通过getContentView().setFocusable(true);来设置PopupWindow的焦点.一般设置为true,因为false的话,弹出框不影响当前界面的操作,像不存在一样;注意,假如PopupWindow布局中有editText这种需要焦点的view的话,就必须设置为true.