1. 程式人生 > >Android6.0之前和之後設定PopupWindow點開空白和返回鍵消失和禁止消失的設定

Android6.0之前和之後設定PopupWindow點開空白和返回鍵消失和禁止消失的設定

    protected void popupIN(View v, Window window, LayoutInflater inflater,  Context context) {
        this.context=context;
        this.window = window;
        this.inflater = inflater;
        final int mWidth;
        final int mHeight;

        contentView = inflater.inflate(R.layout.popup_in, null);
        pWindow = new android.widget.PopupWindow(contentView, LayoutParams.MATCH_PARENT, -1);
        // backgroundAlpha(0.5f);
       // pWindow.setAnimationStyle(R.style.popupwin_style);

        mWidth = contentView.getWidth();
        mHeight = contentView.getHeight();

        pWindow.setFocusable(true); // 獲取焦點
        pWindow.setOutsideTouchable(false);

        pWindow.getContentView().setFocusableInTouchMode(true);
//6.0之前,返回鍵的控制
        pWindow.getContentView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                   // popupWindow.dismiss();

                    return false;
                }
                return false;
            }
        });

        //在Android 6.0以上 ,只能通過攔截事件來解決
        pWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                final int x = (int) event.getX();
                final int y = (int) event.getY();

                if ((event.getAction() == MotionEvent.ACTION_DOWN)
                        && ((x < 0) || (x >= mWidth) || (y < 0) || (y >= mHeight))) {
                    // donothing
                    // 消費事件
                    return false;
                } else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    Log.e(TAG,"out side ...");
                    return true;
                }
                return false;
            }

        });
        pWindow.setInputMethodMode(android.widget.PopupWindow.INPUT_METHOD_NEEDED);
        pWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        radioGroup = contentView.findViewById(R.id.RadioGroup);
        radioGroup.setOnCheckedChangeListener(rrr);
        height = contentView.findViewById(R.id.in_height);
        age = contentView.findViewById(R.id.in_age);
        name = contentView.findViewById(R.id.in_name);

        next = contentView.findViewById(R.id.next);
        backSex =1;
        next.setOnClickListener(ccc);

        pWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        pWindow.setOnDismissListener(new android.widget.PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                //backgroundAlpha(1f);
            }
        });


    }