1.) 让PopupWindow以下拉方式显示在指定位置

这个简单,PopupWindow提供了showAsDropDown,如


[java] view plain copy

 在CODE上查看代码片派生到我的代码片

  1. mPopupWindow.showAsDropDown(mAnchorView, 00);  


mAchorView是一个基准,popupWindow会显示在它的下面。当然也可以显示在它的上面或者左面和右面,这个可以通过其他方法和参数控制。



2。做出类似对话框的背景半透效果

1) 设置PopupWindow全屏:


[java] view plain copy

 在CODE上查看代码片派生到我的代码片

  1. mPopupWindow.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);  

  2. mPopupWindow.setHeight(ViewGroup.LayoutParams.MATCH_PARENT);  



2) 设置背景

背景有两中方式,一种方式是通过mPopupWindow.setBackgroundDrawable, 一种方式是增加一个自己的容器,如FrameLayout。

建议增加自己的容器,因为后面我们要处理touch事件,让窗口关闭。设置容器通过


[java] view plain copy

 在CODE上查看代码片派生到我的代码片

  1. mPopupWindow.setContentView(mContainer);  


3) 处理touch事件,当touch在非内容区域时,popup窗口关闭

非内容区域分两类:半透明区域,这是在容器上的;透明区域,这一部分在popup窗口外。之所以出现这种情况,是在调用showAsDropDown后,AnchorView之上的区域没有被Popupwindow覆盖。

所以首先:


[java] view plain copy

 在CODE上查看代码片派生到我的代码片

  1. mPopupWindow.setFocusable(true);  

这样,让PopupWindow能够接受全屏的touch事件,然后,处理容器的touch事件



[java] view plai

 在CODE上查看代码片派生到我的代码片

  1. private class ContainerView extends FrameLayout {  

  2.        public ContainerView(Context context, AttributeSet attrs, int defStyle) {  

  3.            super(context, attrs, defStyle);  

  4.        }  

  5.   

  6.        @Override  

  7.        public boolean onTouchEvent(MotionEvent event) {  

  8.            if (!super.onTouchEvent(event)) {  

  9.                if (event.getAction() == event.ACTION_UP) {  

  10.                    dismiss();  

  11.                }  

  12.            }  

  13.            return true;  

  14.        }  

  15.    }