记录Android开发中测量view宽高的几种方法

2018-04-10  本文已影响0人  小牛的回忆
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;
    }
}
上一篇下一篇

猜你喜欢

热点阅读