Android在指定View的下方显示PopupWindow

今天工作不忙,所以就把这些年做Android开发的一些经验技巧陆续写到博客上,一来是做自己的备忘,二来是可以帮助大家提高自己的技能。

大家在做下面的弹出层时用的应该都是android的PopupWindow吧(不排除有人直接用ListView盖在上面的),

那么PopupWindow是怎么显示在“全部商圈”的正下方呢?这里就要计算一下了,但是并不是每个人都擅长去计算的。

那我把自己写的计算的代码贴出来,可能写的不够好,如果你有更好的算法,欢迎跟帖。


    public static final int defaultBotom = -100;

    /**
     * @param activity      Activity
     * @param attachOnView  显示在这个View的下方
     * @param popView       被显示在PopupWindow上的View
     * @param popShowHeight 被显示在PopupWindow上的View的高度,可以传默认值defaultBotom
     * @param popShowWidth  被显示在PopupWindow上的View的宽度,一般是传attachOnView的getWidth()
     * @return PopupWindow
     */
    public static PopupWindow show(Activity activity, View attachOnView, View popView, final int popShowHeight, final int popShowWidth) {
        if (popView != null && popView.getParent() != null) {
            ((ViewGroup) popView.getParent()).removeAllViews();
        }

        PopupWindow popupWindow = null;
        Rect frame = new Rect();
        activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

        int location[] = new int[2];
        int x, y;
        int popHeight = 0, popWidth = 0;

        attachOnView.getLocationOnScreen(location);
        x = location[0];
        y = location[1];

        int h = attachOnView.getHeight();
        int screenHeight = DeviceInfoManager.getInstance().getScreenHeight();

        if (popShowHeight == defaultBotom) {
            popHeight = screenHeight / 6;
            popHeight = Math.abs(screenHeight - (h + y)) - popHeight;
        } else if (popHeight == ViewGroup.LayoutParams.WRAP_CONTENT) {
            popHeight = ViewGroup.LayoutParams.WRAP_CONTENT;
        } else {
            popHeight = popShowHeight;
        }

        if (popShowWidth == ViewGroup.LayoutParams.WRAP_CONTENT) {
            popWidth = attachOnView.getWidth();
        } else {
            popWidth = popShowWidth;
        }

        popupWindow = new PopupWindow(popView, popWidth, popHeight, true);

        //这行代码时用来让PopupWindow点击区域之外消失的,这个应该是PopupWindow的一个bug。
        //但是利用这个bug可以做到点击区域外消失
        popupWindow.setBackgroundDrawable(new BitmapDrawable());

        popupWindow.setAnimationStyle(R.style.PopupAnimationDown);
        popupWindow.showAtLocation(attachOnView, Gravity.NO_GRAVITY, x, h + y);
        popupWindow.update();
        return popupWindow;
    }


用的时候大致是这么用:

PopupWindow pop_window = ShowPopList.show(mActivity, mWhichView, mCategoryFilterView, ShowPopList.defaultBotom, -1);

===============================

如果你觉得帮到了你,请给作者打赏一口饭吃:


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值