popupwindow获取宽高

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/y1962475006/article/details/54800136

我们在确定popupwindow的时候会用到
showAtLocation(View parent, int gravity, int x, int y)
api,这个api的入參:
@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
第一个参数为popupwindow所附着的父视图,第二个为gravity,第三第四位window的左上角坐标。
这里gravity需要注意,如果是Gravity.letf|Gravity.top 那么window的坐标就以左上角为原点,如果是Gravity.right|Gravity.top 则是右上角为原点。

很多时候要用到popupwindow 的宽和高来精确放置它,但是经常使用popupwindow.getWidth 值为0 或者 -2。原因是普通的view都会经历Measure-》layout然后显示在window上。popupwindow是响应事件出现的,所以在它出现在屏幕之前,我们是不知道它的大小的。

解决的办法就是在初始化的时候,强制测量它填充的view:
View mContentView = LayoutInflater.from(mContext).inflate(R.layout.XXXX,null);
mContentView.measure(MeasureSpec.UNSPECIFIED,MeasureSpec.UNSPECIFIED);
PopupWindow ppw = new PopUpWindow();
ppw.setContentView(mContentView);

然后要获取ppw的宽和高,只需要ppw.getContentView().getMeasureSpecWidth()就能获取它的宽了。高度也是一样的。

猜你喜欢

转载自blog.csdn.net/y1962475006/article/details/54800136