先来大致介绍写PopupWindow的常规默认状态的几点不好的地方:
1.显示隐藏的时候都是瞬间的,没有任何过度动画。
2.无法通过点击屏幕的空白区域使其关闭。
3.无法在弹窗显示的时候,在其背后加上黑色遮罩。
用过AlertDialog的同学会发现,其实上面三个特性AlertDialog都是自带的效果或通过自带api可以轻松实现,那么我们为什么非要使用PopupWindow呢?那是因为AlertDialog的显示位置非常难调整,并且应为AlertDialog的默认背景是一个sprite9的图片(黑色遮罩),导致他的宽度无法满屏。所以我们需要使用PopupWindow来解决上述问题。
PopupWindow有两种基本的显示方式:
1.显示在某个view的正左下方
/**
* <p>Display the content view in a popup window anchored to the bottom-left
* corner of the anchor view. If there is not enough room on screen to show
* the popup in its entirety, this method tries to find a parent scroll
* view to scroll. If no parent scroll view can be scrolled, the bottom-left
* corner of the popup is pinned at the top left corner of the anchor view.</p>
*
* @param anchor the view on which to pin the popup window
*
* @see #dismiss()
*/
public void showAsDropDown(View anchor) {
showAsDropDown(anchor, 0, 0);
}
/**
* <p>
* Display the content view in a popup window at the specified location. If the popup window
* cannot fit on screen, it will be clipped. See {@link android.view.WindowManager.LayoutParams}
* for more information on how gravity and the x and y parameters are related. Specifying
* a gravity of {@link android.view.Gravity#NO_GRAVITY} is similar to specifying
* <code>Gravity.LEFT | Gravity.TOP</code>.
* </p>
*
* @param parent a parent view to get the {@link android.view.View#getWindowToken()} token from
* @param gravity the gravity which controls the placement of the popup window
* @param x the popup's x location offset
* @param y the popup's y location offset
*/
public void showAtLoc