前言
我们使用PopupWindow时,经常碰见的问题。
1.显示View 的面积不正确。
2.在指定View 的下面或者上面显示时。view弹出位置不正确。
3.如果popupWindow之中的View 视图是list,会根据逻辑变化item时,区域显示的问题。等等。
我也经常碰见这样的问题,所以本篇文章,统一记录下解决方法。一次性解决。
解决方法
首先,让popupwindow的视图View 大小,自适应为你的Layout 设置的dp大小
//自定义PopupWindow 继承系统的PopupWindow
private void initLayout(){
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
linearLayout = new LinearLayout(mContext);
linearLayout.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
dismiss();
return false;
}
});
layout = inflater.inflate(layoutIds, linearLayout);
this.setContentView(linearLayout);
initView(layout); //在这个方法里面 可以findViewById 去写得到的view
popConfig(layout);
//设置点击popupwindow 外部区域可以透传,并销毁PopupWindows
setBackgroundDrawable(new ColorDrawable(0x00000000));
setOutsideTouchable(true);
}
public void popConfig(View view) {
view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
popupHeight = view.getMeasuredHeight();
popupWidth = view.getMeasuredWidth();
}
@Override
public void dismiss() {
time = System.currentTimeMillis();
super.dismiss();
}
//下面 创建一个在指定View 上显示的浮动
public boolean showTopPopupWindow(View anchor) {
//显示浮动框
if (this.isShowing()) {
this.dismiss();
return false;
}
//这个时间 主要是记录,在外部点击时popupwindow销毁然后再创建,的问题 在dismiss 下记录下time 的时间
if (time + 150 > System.currentTimeMillis()) {
return false;
}
int[] location = new int[2];
anchor.getLocationOnScreen(location);
int x = location[0];
int y = location[1] - popupHeight - 10;
showAtLocation(anchor, Gravity.NO_GRAVITY, x
, y);
return true;
}
评论区