控件的寬高獲取

PopupWindow在創建時寬度高度設置爲match_parent或者wrap_content時,通過getWidth、getHeight或者getContentView.getMeasuredWidth、getContentView.getMeasuredHeight 不能獲取到真實的高度!

正確的方法獲取高度的方法是創建之後調用measure方法對View進行測量,然後獲取寬度與高度!

示例:

[java] view plain copy
 在CODE上查看代碼片派生到我的代碼片
  1. View popupWindowView = View.inflate(getContext(), R.layout.popupwindow_layout, null);  
  2. PopupWindow popupWindow=new PopupWindow(popupWindowView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);  
  3.         popupWindow.getContentView().measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);  
  4.         popupWindow.setBackgroundDrawable(new ColorDrawable(0));  
  5.         int popHeight=popupWindow.getContentView().getMeasuredHeight();  
  6.         popupWindow.showAsDropDown(view, 0, -popHeight);  

其他彈出類的窗口類似!在獲取width與height之前先進行測量!

發佈了21 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章