控件的宽高获取

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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章