侧边栏壁纸
  • 累计撰写 416 篇文章
  • 累计创建 65 个标签
  • 累计收到 150 条评论

目 录CONTENT

文章目录

Android PopupWindow 对象的使用

Z同学
2020-09-16 / 0 评论 / 1 点赞 / 8,159 阅读 / 1,670 字
温馨提示:
本文最后更新于 2021-11-18,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

前言

我们使用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;
    }

1

评论区