Android中自定义控件-获取View的宽度和高度

1,903 阅读1分钟

在漫长的开发岁月中,你有没有遇到过这种问题,我们对一个布局高度设置了wrap_contant属性,但是在某个地方我们需要获取到它的一个真实的高度,那我们该怎么办呢?这里提供了一种获取某个View高度的方法。

public static float getRealHeight(View child){
    LinearLayout llayout = (LinearLayout) child;
    ViewGroup.LayoutParams params = llayout.getLayoutParams();
    if (params == null){
        params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    }
    int widthSpec = ViewGroup.getChildMeasureSpec(0,0,params.width);
    int heightSpec;
    if (params.height>0){
        heightSpec = View.MeasureSpec.makeMeasureSpec(params.height, View.MeasureSpec.EXACTLY);
    }else {
        heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
    }
    llayout.measure(widthSpec,heightSpec);
    return llayout.getMeasuredHeight();//获取布局高度,获取布局宽度可以调用getMeasuredWidth()
}

这样我们就获取到了对应view的一个高度,宽度可以把 return中的返回内容更改一下就好,简单方便。