获取View的高度和宽度

来源:互联网 发布:淘宝闲鱼1元拍卖翡翠 编辑:程序博客网 时间:2024/05/07 01:29
private void measureView(View child) {            ViewGroup.LayoutParams params = child.getLayoutParams();            if (params == null) {                params = new ViewGroup.LayoutParams(                        ViewGroup.LayoutParams.MATCH_PARENT,                        ViewGroup.LayoutParams.WRAP_CONTENT);            }            int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0,                    params.width);            int lpHeight = params.height;            int childHeightSpec;            if (lpHeight > 0) {                childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,                        MeasureSpec.EXACTLY);            } else {                childHeightSpec = MeasureSpec.makeMeasureSpec(0,                        MeasureSpec.UNSPECIFIED);            }            child.measure(childWidthSpec, childHeightSpec);        }    

直接调用方法就行,传入你需要测量的View对象,比如ListView。

然后通过调用View对象的 getMessuredWidth() 和 getMessuredHeight() 就可以获得宽和高,结果的单位是PX(像素)

0 1