PopupWindow的显示和背景

来源:互联网 发布:c语言for语句continue 编辑:程序博客网 时间:2024/04/19 19:04
private void showWindow(View parent) {          if (popupWindow == null) {              LayoutInflater layoutInflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);              View  view = layoutInflater.inflate(自定义的XML, null);              popupWindow = new PopupWindow(view,500, 400);//实例化一个popupwindow大小(LayoutParams.WRAP_CONTENT自适应大小)        }          popupWindow.setFocusable(true);  //设置PopupWindow可获得焦点        popupWindow.setOutsideTouchable(true);  //设置非PopupWindow区域可触摸//设置背景变暗        popupWindow.setBackgroundDrawable(new BitmapDrawable());  WindowManager  windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);         WindowManager.LayoutParams lp = getWindow().getAttributes();          lp.alpha = 0.4f; //0.0-1.0          getWindow().setAttributes(lp);         popupWindow.setOnDismissListener(new poponDismissListener());         //设置背景变暗完        // 显示的位置为:屏幕的宽度的一半-PopupWindow的高度的一半          int xPos = windowManager.getDefaultDisplay().getWidth() / 2                  - popupWindow.getWidth() / 2;          Log.i("coder", "xPos:" + xPos);         int[] location = new int[2];          parent.getLocationOnScreen(location);  
/**popupWindow显示的位置有三种,简单说下,showAsDropDown(anchor),showAsDropDown(anchor, xoff, yoff),showAtLocation(parent, gravity, x, y);前两个showAsDropDown方法是让PopupWindow相对于某个控件显示,而showAtLocation是相对于整个窗口的。第一个参数是View类型的parent,虽然这里参数名是parent,其实,不是把PopupWindow放到这个parent里,并不要求这个parent是一个ViewGroup,这个参数名让人误解。官方文档”a parent view to get the android.view.View.getWindowToken() token from“,这个parent的作用应该是调用其getWindowToken()方法获取窗口的Token,所以,只要是该窗口上的控件就可以了。第二个参数是Gravity,可以使用|附加多个属性,如Gravity.LEFT|Gravity.BOTTOM。第三四个参数是x,y偏移。**/
popupWindow.showAtLocation(parent, Gravity.CENTER, 0,0);      //popupWindow.showAsDropDown(parent, xPos, 0);      }     /**    popupWindow出来之后其他地方变暗    */    class poponDismissListener implements PopupWindow.OnDismissListener{          @Override          public void onDismiss() {              //Log.v("List_noteTypeActivity:", "我是关闭事件");              WindowManager.LayoutParams lp = getWindow().getAttributes();              lp.alpha = 1f; //0.0-1.0              getWindow().setAttributes(lp);         }      }//点击其他地方消失popupWindow.setOutsideTouchable(true);        // 自定义view添加触摸事件        layoutInflater.setOnTouchListener(new OnTouchListener() {            @Override            public boolean onTouch(View v, MotionEvent event) {                if (event.getAction() != MotionEvent.ACTION_OUTSIDE) {                    popupWindow.dismiss();                      popupWindow = null;                      return true;                }                return false;            }        });
0 0
原创粉丝点击