Android popupWindow的简单应用

//          该界面的最外层viewGroup
        activity_main2 = (RelativeLayout) findViewById(R.id.activity_main2);

        btn_popUpWindow= (TextView) findViewById(R.id.btn_popUpWindow);
        btn_popUpWindow.setOnClickListener(this);

        View popView = LayoutInflater.from(this).inflate(R.layout.layout_popupwindow, null);
        popupWindow = new PopupWindow(popView, WindowManager.LayoutParams.MATCH_PARENT,WindowManager.LayoutParams.WRAP_CONTENT);
        // 设置popWindow弹出窗体可点击,这句话必须添加,并且是true
        popupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明,否则点击popupWindow外部、返回键popupWindow不会取消
        ColorDrawable dw = new ColorDrawable(Color.WHITE);
        popupWindow.setBackgroundDrawable(dw);

        btn_1= (Button) popView.findViewById(R.id.btn_1);
        btn_1.setOnClickListener(this);
        btn_2= (Button) popView.findViewById(R.id.btn_2);
        btn_2.setOnClickListener(this);

        btn_cancel= (Button) popView.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(this);
@Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btn_popUpWindow:
//          软键盘不会挡着popupwindow(必须在弹出popUpWindow弹出之前使用才有效果)
                popupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//          点击后popupWindow由下向上弹出
                popupWindow.showAtLocation(activity_main2,
                        Gravity.BOTTOM, 0, 0);
                break;
            case R.id.btn_popBottom:
//          点击后popupWindow在btn_popBottom下方弹出
                popupWindow.showAsDropDown(btn_popBottom);
                break;
            case R.id.btn_popTop:
                //获取popView自身的长宽高
                popView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                int popupWidth = popView.getMeasuredWidth();
                int popupHeight = popView.getMeasuredHeight();
                Log.e("Tag","popUpWindow popupWidth---"+popupWidth+",popupHeight---"+popupHeight);
//            获取点击btn_popWindows的坐标
                int[] location = new int[2];
                btn_popTop.getLocationOnScreen(location);
                Log.e("Tag","location[0]---"+location[0]+",location[1]---"+location[1]);
                popupWindow.showAtLocation(btn_popTop, Gravity.NO_GRAVITY, location[0], location[1]-popupHeight);
                break;
            case R.id.btn_1:
                Log.e("Tag","11111111");
                break;
            case R.id.btn_2:
                Log.e("Tag","22222222");
                break;
            case R.id.btn_cancel:
//          点击popupWindow中的取消按钮,popupWindow取消
                popupWindow.dismiss();
                break;
        }
    }

你可能感兴趣的:(Android popupWindow的简单应用)