在使用popupWindow的時候發(fā)現(xiàn)一個問題:
mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
由于顯示的頁面的長寬是不確定的,所以只能使用wrap_content。但是在使用wrap_content時候會出現(xiàn)顯示不完整的問題,可見其在measure的時候會出現(xiàn)問題。
一開始的時候,設(shè)想通過content_view的getMeasureWidth(),getMeasuredHeight()獲取長寬,發(fā)現(xiàn)獲取到的為0,原因是在獲取長寬的時候,content_view的measure還未完成。
解決方法:先進行measure再次獲取getMeasureWidth()
比較完整代碼:
public class MyPopupView {
private Context mContext;
private PopupWindow mPopupWindow;
private View mRootView;
private boolean isShowing;
public MyPopupView(View rootView, Context mContext){
this.mContext = mContext;
this.mRootView = rootView;
this.isShowing = false;
}
public void showView(){
if(isShowing == true)
return;
if (mPopupWindow == null){
View contentView = LayoutInflater.from(mContext).inflate(R.layout.popup_view,null);
contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
mPopupWindow = new PopupWindow(contentView, contentView.getMeasuredWidth(), ViewGroup.LayoutParams.WRAP_CONTENT);
// mPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT);
mPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
mPopupWindow.setFocusable(true);
}
isShowing = true;
mPopupWindow.showAsDropDown(mRootView);//以contentview為參照系
// 或者 mPopupWindow.showAtLocation();
}
}