View在属性为wrap_content/match_parent时获取宽高不准确的解决办法

来源:互联网 发布:qq飞车淘宝包中真的吗 编辑:程序博客网 时间:2024/06/07 06:28

View 或ViewGroup在创建时设置宽度高度为match_parent或者wrap_content时,通过getWidth()、getHeight()或者getMeasuredWidth()、getMeasuredHeight()不能获取到真实的宽高.

正确的方法获取高度的方法是创建之后调用measure方法对View进行测量,然后获取宽度与高度!

示例:

LinearLayout ll_login_container = (LinearLayout) rootView.findViewById(R.id.ll_login_container);ll_login_container.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);int height = ll_login_container.getMeasuredHeight();int width = ll_login_container.getMeasuredWidth();

其他如PopupWindow,弹框等也是类似,获取width/height之前需要先measure!

阅读全文
0 0
原创粉丝点击