部分内容本文内容转载自
http://www.cnblogs.com/mengdd/p/3569127.html
1.两种显示方式:
1)showAtLocation(View parent, int gravity, int x, int y)
第一个参数是View类型的parent,虽然这里参数名是parent,其实,不是把PopupWindow放到这个parent里,并不要求这个parent是一个ViewGroup,这个参数名让人误解。官方文档”a parent view to get the android.view.View.getWindowToken() token from“,这个parent的作用应该是调用其getWindowToken()方法获取窗口的Token,所以,只要是该窗口上的控件就可以了
2)showAsDropDown(View anchor, 0, 0)
显示在一个参照物View的周围,默认是将PopupWindow 的左上角与 anchor 的左下角对齐的,如果anchor过于靠右,导致二者无法实现左侧线对齐,则 PopupWindow 右侧顶着屏幕右边缘放置。
在控件的上方:
int[] location = new int[2];
v.getLocationOnScreen(location);
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0], location[1]-popupWindow.getHeight());
下方:
popupWindow.showAsDropDown(v);
左边:
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]-popupWindow.getWidth(), location[1]);
右边:
popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, location[0]+v.getWidth(), location[1]);
2.使popwindow外部区域点击其无法消失方法:
// 这里如果返回true的话,touch事件将被拦截
// 拦截后 PopupWindow的onTouchEvent不被调用,这样点击外部区域无法dismiss
popupWindow.setTouchInterceptor(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
Log.i("mengdd", "onTouch : ");
return true;
}
});
3.点击外部区域还是Back键都无法dismiss弹框问题
解决:设置PopupWindow的背景: popupWindow.setBackgroundDrawable
原因:弹出popwindow需要调用preparePopup()方法,上源码:
/**
* <p>Prepare the popup by embedding in into a new ViewGroup if the
* background drawable is not null. If embedding is required, the layout
* parameters' height is mnodified to take into account the background's
* padding.</p>
*
* @param p the layout parameters of the popup's content view
*/
private void preparePopup(WindowManager.LayoutParams p) {
if (mContentView == null || mContext == null || mWindowManager == null) {
throw new IllegalStateException("You must specify a valid content view by "
+ "calling setContentView() before attempting to show the popup.");
}
if (mBackground != null) {
final ViewGroup.LayoutParams layoutParams = mContentView.getLayoutParams();
int height = ViewGroup.LayoutParams.MATCH_PARENT;
if (layoutParams != null &&
layoutParams.height == ViewGroup.LayoutParams.WRAP_CONTENT) {
height = ViewGroup.LayoutParams.WRAP_CONTENT;
}
// when a background is available, we embed the content view
// within another view that owns the background drawable
PopupViewContainer popupViewContainer = new PopupViewContainer(mContext);
PopupViewContainer.LayoutParams listParams = new PopupViewContainer.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, height
);
popupViewContainer.setBackgroundDrawable(mBackground);
popupViewContainer.addView(mContentView, listParams);
mPopupView = popupViewContainer;
} else {
mPopupView = mContentView;
}
mPopupViewInitialLayoutDirectionInherited =
(mPopupView.getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT);
mPopupWidth = p.width;
mPopupHeight = p.height;
}
由以上源码可以知道: 如果有背景,则会在contentView外面包一层PopupViewContainer之后作为mPopupView,如果没有背景,则直接用contentView作为mPopupView
而这个PopupViewContainer是一个内部私有类,它继承了FrameLayout,在其中重写了Key和Touch事件的分发处理,上源码:
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
if (getKeyDispatcherState() == null) {
return super.dispatchKeyEvent(event);
}
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getRepeatCount() == 0) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null) {
state.startTracking(event, this);
}
return true;
} else if (event.getAction() == KeyEvent.ACTION_UP) {
KeyEvent.DispatcherState state = getKeyDispatcherState();
if (state != null && state.isTracking(event) && !event.isCanceled()) {
dismiss();
return true;
}
}
return super.dispatchKeyEvent(event);
} else {
return super.dispatchKeyEvent(event);
}
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
if (mTouchInterceptor != null && mTouchInterceptor.onTouch(this, ev)) {
return true;
}
return super.dispatchTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
final int x = (int) event.getX();
final int y = (int) event.getY();
if ((event.getAction() == MotionEvent.ACTION_DOWN)
&& ((x < 0) || (x >= getWidth()) || (y < 0) || (y >= getHeight()))) {
dismiss();
return true;
} else if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
dismiss();
return true;
} else {
return super.onTouchEvent(event);
}
}
由于PopupView本身并没有重写Key和Touch事件的处理,所以如果没有包这个外层容器类,点击Back键或者外部区域是不会导致弹框消失的。
补充Case: 弹窗不消失,但是事件向下传递
如上所述:
设置了PopupWindow的background,点击Back键或者点击弹窗的外部区域,弹窗就会dismiss.
相反,如果不设置PopupWindow的background,那么点击back键和点击弹窗的外部区域,弹窗是不会消失的.
那么,如果我想要一个效果,点击外部区域,弹窗不消失,但是点击事件会向下面的activity传递,比如下面是一个WebView,我想点击里面的链接等.
研究了半天,说是要给Window设置一个Flag,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
看了源码,这个Flag的设置与否是由一个叫mNotTouchModal的字段控制,但是设置该字段的set方法被标记为@hide。
所以要通过反射的方法调用:
/**
* Set whether this window is touch modal or if outside touches will be sent
* to
* other windows behind it.
*
*/
public static void setPopupWindowTouchModal(PopupWindow popupWindow,
boolean touchModal) {
if (null == popupWindow) {
return;
}
Method method;
try {
method = PopupWindow.class.getDeclaredMethod("setTouchModal",
boolean.class);
method.setAccessible(true);
method.invoke(popupWindow, touchModal);
}
catch (Exception e) {
e.printStackTrace();
}
}
然后在程序中:
UIUtils.setPopupWindowTouchModal(popupWindow, false); 该popupWindow外部的事件就可以传递给下面的Activity了。
4.PopupWindow的动画
很多时候我们把PopupWindow用作自定义的菜单,需要一个从底部向上弹出的效果,这就需要为PopupWindow添加动画。
设置动画的方法:
public void setAnimationStyle(int animationStyle);
在res/value/styles.xml添加一个sytle
<style name="anim_menu_bottombar">
<item name="android:windowEnterAnimation">@anim/menu_bottombar_in</item>
<item name="android:windowExitAnimation">@anim/menu_bottombar_out</item>
</style>
在工程res下新建anim文件夹,在anim文件夹先新建两个xml文件
menu_bottombar_in.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="250"
android:fromYDelta="100.0%"
android:toYDelta="0.0" />
</set>
menu_bottombar_out.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
<translate
android:duration="250"
android:fromYDelta="0.0"
android:toYDelta="100%" />
</set>
mPopupWindow.setAnimationStyle(R.style.menu_anim_bottombar);