popupWindow的实际使用

2016-12-15 10:41

这里写图片描述

 /**
 * 弹出popupWindow
 */
    private void showPopupWindown() {
        //新建popupWindow实例
        View view = LayoutInflater.from(this).inflate(R.layout.view_popupwindow_choose_reason, null);
        final PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);

        //这些为了点击非PopupWindow区域,PopupWindow会消失的,如果没有下面的
        //代码的话,你会发现,当你把PopupWindow显示出来了,无论你按多少次后退键
        //PopupWindow并不会关闭,而且退不出程序,加上下述代码可以解决这个问题
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
                // 这里如果返回true的话,touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
            }
        });
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效

        //设置添加屏幕的背景透明度
        setBackgroundAlpha(0.5f);//0.0-1.0

        //popupWindow消失时,背景恢复正常
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
            }
        });

        //popupWindow里的项添加点击监听
        TextView tv1 = (TextView) view.findViewById(R.id.pop_window_tv_reason_1);
        TextView tv2 = (TextView) view.findViewById(R.id.pop_window_tv_reason_2);
        TextView tv3 = (TextView) view.findViewById(R.id.pop_window_tv_reason_3);
        TextView tv4 = (TextView) view.findViewById(R.id.pop_window_tv_reason_4);
        TextView[] tvArray = {tv1,tv2,tv3,tv4};
        for (int i = 0;i<tvArray.length;i++){
            final TextView tv = tvArray[i];
            tv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    popupWindow.dismiss();
                    setBackgroundAlpha(1f);
                    String str = tv.getText().toString().trim();
                    mTvReason.setText(str);
                    mTvReason.setTextColor(Color.parseColor("#3D4245"));
                }
            });
        }

        //弹出popupWindow
        popupWindow.showAtLocation(mWhole, Gravity.CENTER, 0, 0);
    }

    /**
 * 设置添加屏幕的背景透明度
 *
 * @param bgAlpha
 */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
    }