1. 程式人生 > >popupwindow獲取寬高

popupwindow獲取寬高

我們在確定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()就能獲取它的寬了。高度也是一樣的。