public class ViewMeasureUtil {
private ViewMeasureUtil() {
}
//在Activity的onCreate()方法中获取view的尺寸
public static void measureSize(View view, ViewTreeObserver.OnGlobalLayoutListener listener) {
ViewTreeObserver observer = view.getViewTreeObserver();
observer.addOnGlobalLayoutListener(listener);
}
//自定义控件,重写onMeasure()方法
public static int measureWidth(int measureSpec, int defaultWidth) {
return measure(measureSpec, defaultWidth);
}
//自定义控件,重写onMeasure()方法
public static int measureHeight(int measureSpec, int defaultHeight) {
return measure(measureSpec, defaultHeight);
}
private static int measure(int measuerSpec, int defaultSize) {
int result;
int specMode = View.MeasureSpec.getMode(measuerSpec);
int specSize = View.MeasureSpec.getSize(measuerSpec);
if (specMode == View.MeasureSpec.EXACTLY) {
result = specSize;
} else {
result = defaultSize;
if (specMode == View.MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
}
网友评论