简易封装的PopupWindow

import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.PopupWindow;

import com.msyc.onion.R;

import java.lang.ref.WeakReference;

/**
 * 简易封装的PopupWindow
 */

public class CustomPopupWindow implements PopupWindow.OnDismissListener {
    private PopupWindow mPopupWindow;
    private View contentView;
    private static WeakReference<Activity> refActivity;
    private Builder builder;

    public CustomPopupWindow(Builder builder) {
        this.builder = builder;
        contentView = LayoutInflater.from(refActivity.get()).inflate(builder.contentViewId, null);
        mPopupWindow = new PopupWindow(contentView, builder.width, builder.height);
        if (builder.outsideTouchable) {
            //设置点击外部可以取消,必须和下面这个方法配合才有效,(setOutsideTouchable设置生效的前提是setTouchable(true)和setFocusable(false),此处存疑)
            mPopupWindow.setOutsideTouchable(true);
            //设置一个空背景,设置了这个背景之后,设置点击外部取消才有效
            mPopupWindow.setBackgroundDrawable(new ColorDrawable()); //如果不设置PopupWindow的背景,有些版本就会出现一个问题:无论是点击外部区域还是Back键都无法dismiss弹框
//            mPopupWindow.setTouchable(true);
            mPopupWindow.setFocusable(true); // false时PopupWindow不处理返回键(此处设置为true,则效果是正常的,和上方的说法存疑)
        }
        //Popupwindow可以点击,PopupWindow弹出后,所有的触屏和物理按键都有PopupWindows处理。
        // 其他任何事件的响应都必须发生在PopupWindow消失之后, (home  等系统层面的事件除外)。
        // 比如这样一个PopupWindow出现的时候,按back键首先是让PopupWindow消失,
        // 第二次按才是退出activity,
        //解决Pop遮挡住虚拟键盘的问题
        mPopupWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
        //让pop自适应输入状态
        mPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (builder.animStyle != 0) {
            mPopupWindow.setAnimationStyle(builder.animStyle); //设置pop显示的动画效果
        }
        mPopupWindow.setOnDismissListener(this); //设置pop关闭的监听事件

        // 原生的Outside 事件会穿透到下方(原生问题),故用gray_layout多做一层补充作用(主要用于点击消失popwindow,避免事件穿透)
        if (contentView.findViewById(R.id.gray_layout) != null) {
            View grayLayout = (View) contentView.findViewById(R.id.gray_layout);
            grayLayout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    /**
     * popup 消失
     */
    public void dismiss() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }


    /**
     * 相对于窗体的显示位置
     *
     * @param view    可以为Activity中的任意一个View(最终的效果一样),
     *                会通过这个View找到其父Window,也就是Activity的Window。
     * @param gravity 在窗体中的位置,默认为Gravity.NO_GRAVITY
     * @param x       表示距离Window边缘的距离,方向由Gravity决定。
     *                例如:设置了Gravity.TOP,则y表示与Window上边缘的距离;
     *                而如果设置了Gravity.BOTTOM,则y表示与下边缘的距离。
     * @param y
     * @return
     */
    public CustomPopupWindow showAtLocation(View view, int gravity, int x, int y) {
        if (mPopupWindow != null) {
            mPopupWindow.showAtLocation(view, gravity, x, y);
            if (builder != null) setBackgroundAlpha(builder.backgroundAlpha); //设置窗体的背景透明度为半透明
        }
        return this;
    }


    /**
     * 显示在anchor控件的正下方,或者相对这个控件的位置
     *
     * @param anchor 锚点
     * @param xOff   相对这个控件x方向的偏移
     * @param yOff   相对这个控件y方向的偏移
     * @return
     */
//    public CustomPopupWindow showAsDropDown(View anchor, int xOff, int yOff) {
//        if (mPopupWindow != null) {
//            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                //7.0以上系统
//                //获取目标控件在屏幕中的坐标位置
//                int[] location = new int[2];
//                anchor.getLocationOnScreen(location);
//                mPopupWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, 0, location[1] + anchor.getHeight() + yOff);
//            } else {
//                mPopupWindow.showAsDropDown(anchor, xOff, yOff);
//            }
//            if (builder != null) setBackgroundAlpha(builder.backgroundAlpha); //设置窗体的背景透明度为半透明
//        }
//        return this;
//    }
    public CustomPopupWindow showAsDropDown(View anchor, int xOff, int yOff) {
        if (mPopupWindow != null) {
            if (!mPopupWindow.isShowing()) {
                // 以下拉方式显示popupwindow
                mPopupWindow.showAsDropDown(anchor, xOff, yOff);
                if (builder != null) setBackgroundAlpha(builder.backgroundAlpha); //设置窗体的背景透明度为半透明
            }
//            else {
//                this.dismiss();
//            }
        }
        return this;
    }

    public CustomPopupWindow showAsDropDown(View anchor) {
        if (mPopupWindow != null) {
            if (!mPopupWindow.isShowing()) {
                // 以下拉方式显示popupwindow
                mPopupWindow.showAsDropDown(anchor);
                if (builder != null) setBackgroundAlpha(builder.backgroundAlpha); //设置窗体的背景透明度为半透明
            }
//            else {
//                this.dismiss();
//            }
        }
        return this;
    }

    /**
     * 根据id获取view
     *
     * @param viewId
     * @return
     */
    public View getItemView(int viewId) {
        if (mPopupWindow != null) {
            return contentView.findViewById(viewId);
        }
        return null;
    }


    /**
     * 根据id设置pop内部的控件的点击事件的监听
     *
     * @param viewId
     * @param listener
     */
    public void setOnClickListener(int viewId, View.OnClickListener listener) {
        View view = getItemView(viewId);
        view.setOnClickListener(listener);
    }

    /**
     * 设置Activity或者Fragment的背景透明度
     *
     * @param bgAlpha 背景的透明度
     */
    public void setBackgroundAlpha(float bgAlpha) {
        if (refActivity.get() == null || refActivity.get().getWindow() == null) return;
        WindowManager.LayoutParams layoutParams = refActivity.get().getWindow().getAttributes();
        layoutParams.alpha = bgAlpha; //0.0-1.0
        refActivity.get().getWindow().setAttributes(layoutParams);
    }

    /**
     * builder 类
     */
    public static class Builder {
        private int contentViewId; //pop的布局文件
        private int width; //pop的宽度
        private int height;  //pop的高度
        private int animStyle; //动画效果
        private float backgroundAlpha = 0.5f; //背景的透明度,默认半透明
        private boolean outsideTouchable = false; //设置点击外部可以取消

        public Builder(Activity activity) {
            refActivity = new WeakReference<>(activity);
        }

        public Builder setContentView(int contentViewId) {
            this.contentViewId = contentViewId;
            return this;
        }

        public Builder setwidth(int width) {
            this.width = width;
            return this;
        }

        public Builder setheight(int height) {
            this.height = height;
            return this;
        }


        public Builder setAnimationStyle(int animStyle) {
            this.animStyle = animStyle;
            return this;
        }

        public Builder setBackgroundAlpha(float backgroundAlpha) {
            this.backgroundAlpha = backgroundAlpha;
            return this;
        }

        public Builder setOutsideTouchable(boolean touchable) {
            outsideTouchable = touchable;
            return this;
        }

        public CustomPopupWindow build() {
            return new CustomPopupWindow(this);
        }
    }

    @Override
    public void onDismiss() {
        if (builder == null || builder.backgroundAlpha != 1f)
            setBackgroundAlpha(1f); //设置窗体的背景透明度为不透明
    }
}

使用方法:

private CustomPopupWindow mSearchDropPop; 

/**
     * 初始化Pop,pop的布局是一个列表
     */
    private void initPop() {
        if (mSearchDropPop == null || mSearchDropAdapter == null) {
            mSearchDropPop = new CustomPopupWindow.Builder(this)
                    .setContentView(R.layout.search_drop_pop_window)
                    .setwidth(LinearLayout.LayoutParams.MATCH_PARENT)
                    .setheight(LinearLayout.LayoutParams.WRAP_CONTENT)
                    .setBackgroundAlpha(1.0f)
                    .build();
            //搜索联想结果的列表
            ListView searchLv = (ListView) mSearchDropPop.getItemView(R.id.lv_search_list);
            mSearchDropAdapter = new SearchDropAdapter(this, null);
            searchLv.setAdapter(mSearchDropAdapter);
            searchLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    mBinding.editTextSearch.setText(mSearchDropAdapter.getList().get(position).text);
                    mKeyword = mSearchDropAdapter.getList().get(position).text;
                    preSearch().search(mSearchDropAdapter.request_id); // 点击联想词
                }
            });
        }
    }

/**关键字联想词*/
        mViewModel.mSearchDropData.observe(this, result -> {
            if (result == null || result.getBeanList().size() <= 0) {
                mSearchDropPop.dismiss();
            } else {
                String s = mBinding.editTextSearch.getText().toString();
                if (s.length() > 0 && s.equals(mmSearchDropWord)) {
                    mSearchDropAdapter.setDatas(result);
                    mSearchDropAdapter.notifyDataSetChanged();
                    mSearchDropPop.showAsDropDown(mBinding.editTextSearch); 
                }
            }
        });

@Override
    protected void onDestroy() {
        if (mSearchDropPop != null) {
            mSearchDropPop.dismiss();
        }
        super.onDestroy();
    }

xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#66000000"
    android:orientation="vertical">

    <ListView
        android:id="@+id/lv_search_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:divider="@null"
        android:paddingTop="@dimen/dp_6" />
    <!--该View用来撑满屏幕用 显示灰色透明背景-->
    <View
        android:id="@+id/gray_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#F1F2F4" />

</LinearLayout>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267