问题:
想实现的效果是PopupWindow占据某个控件以下的区域;但是如果PopupWindow宽或者高设置MatchParent时,showAsDropDown方法会失效,PopupWindow会占满全屏。
解决方案(动态设置据顶部的距离):
1.显示前设置固定高度为屏幕底部到控件距离:
TextView title = findViewById(R.id.popup_title);
int[] location = new int[2];
title.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
popup.setHeight(MyApplication.instance.getResources().getDisplayMetrics().heightPixels - y);
popup.showAsDropDown(title);
2.显示前设置内部根元素的marginTop为屏幕上方到控件的距离:
int[] location = new int[2];
title.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
// popup.setHeight(SmartHomeApplication.instance.getResources().getDisplayMetrics().heightPixels - y);
//设置popupwindow背景透明,自己在布局中写背景
popup.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
popup.showAsDropDown(title);
popup.setContentMarginTop(y + CommonUtils.getStatusBarHeight(SmartHomeApplication.instance));
//popup中添加方法:
public void setContentMarginTop(int marginTop) {
((FrameLayout.LayoutParams) root.getLayoutParams()).setMargins(0, marginTop, 0,0);
}
获取statusBar高度:
https://blog.csdn.net/divaid/article/details/110431790
注:
获取到控件x跟y位置后建议保存下来,因为每次调用getLocationOnScreen会遍历控件父控件获取左边距与上边距,会浪费一定时间,见下图。