好久没写博客了,来一篇有问题搞不懂就要看!源!码!系列
之前一直搞不懂为什么PopupWindow一定要设置Background才能实现点击其他地方消失的效果,后来在老师的带领下看了下源码,豁然开朗(虽然还有些地方搞不懂)。
在PopupWindow类里有一个方法叫preparePopup(),对mBackground做了判断,若其不为空,则将mContentView嵌入到一个PopupViewContainer中。否则不执行此操作。具体代码如下:
-
/**
-
* <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 modified 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.setBackground(mBackground);
-
popupViewContainer.addView(mContentView, listParams);
-
-
mPopupView = popupViewContainer;
-
} else {
-
mPopupView = mContentView;
-
}
-
-
mPopupView.setElevation(mElevation);
-
mPopupViewInitialLayoutDirectionInherited =
-
(mPopupView.getRawLayoutDirection() == View.LAYOUT_DIRECTION_INHERIT);
-
mPopupWidth = p.width;
-
mPopupHeight = p.height;
-
}
再看下PopupViewContainer的代码:
它里面注册了Touch事件,这下就大概明白了。如果我们不设置background的话,mContentView就不会被放入PopupViewContainer,
自然响应不了触摸事件,也就不会消失了。具体还是看代码吧:
所以说,源码才是王道。但我搞不懂的地方是,为啥一定要设置了背景才把mContentView加到PopupViewContainer中,有了解的朋友们请指教。
阅读(1215) | 评论(0) | 转发(0) |