PopupWindow
两个方法:showAtLocation(相对于组件parent屏幕)和showAsDropDown(相对于组件)
showAtLocation:
public void showAtLocation(View parent, int gravity, int x, int y)parent可以为Activity中的任意一个View(最终的效果一样),会通过这个View找到其父Window,也就是Activity的Window。
gravity,默认为Gravity.NO_GRAVITY,等效于Gravity.LEFT | Gravity.TOP
x, y,边距。这里的x,y表示距离Window边缘的距离,方向由Gravity决定。例如:设置了Gravity.TOP,则y表示与Window上边缘的距离;而如果设置了Gravity.BOTTOM,则y表示与下边缘的距离。
如果弹窗位置超出了Window的范围,会自动处理使其处于Window中
相对于屏幕(左上角0,0),窗位置超出了Window的范围,会自动处理使其处于Window中,显示范围是顶部和底部
注意使用的时候,如果设置Gravity.TOP,则要计算状态栏的高度
注意:在Android7.0此方法不生效,如果想在屏幕中间位置,解决办法在屏幕中间画根线,然后用showAsDropDown相对于这根线做偏移
public void showAsDropDown(View anchor, int xoff, int yoff)
弹窗会显示在anchor控件的正下方。
如果指定了xoff和yoff,则会在原有位置向右偏移xoff,向下偏移yoff。
如果指定gravity为Gravity.RIGHT,则弹窗和控件右对齐;否则左对齐。注意,计算右对齐时使用了- PopupWindow的宽度,如果指定的宽度不是固定值,则计算会失效(可以从源码中看出来)。
如果弹窗位置超出了Window的范围,会自动处理使其处于Window中。
如果anchor可以滚动,则滚动过程中,PopupWindow可以自动更新位置,跟随anchor控件。
相对于组件(左下角 0,屏幕高度)
总结:showAtLocation 和 showAsDropDown 主要区别于显示位置相对于屏幕还是组件
dialog
附上代码,关键
lp.y = high; // 新位置Y坐标
dialog = new Dialog(context, R.style.DialogMore); dialog.setContentView(R.layout.toast_dialog_item); tv = (TextView) dialog.findViewById(R.id.tv_content); tv.setText(contents); //点击dialog旁边空白不关闭 dialog.setCanceledOnTouchOutside(false); //点击回退按钮不关闭 // dialog.setCancelable(false); Window window = dialog.getWindow(); window.setGravity(Gravity.TOP); // 非常重要:设置对话框弹出的位置 window.setWindowAnimations(R.style.DialogMore); //设置窗口弹出动画 // 设置dialog对齐两边 WindowManager windowManager = ((Activity) mContext).getWindowManager(); Display display = windowManager.getDefaultDisplay(); WindowManager.LayoutParams lp = dialog.getWindow().getAttributes(); lp.width = (int) (display.getWidth() * 1.0); //设置宽度 lp.y = high; // 新位置Y坐标
lp.x = 0; // 新位置X坐标dialog.getWindow().setAttributes(lp); dialog.show();