美文网首页
记录Android开发中测量view宽高的几种方法

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

作者: 小牛的回忆 | 来源:发表于2018-04-10 15:24 被阅读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;
        }
    }

    相关文章

      网友评论

          本文标题:记录Android开发中测量view宽高的几种方法

          本文链接:https://www.haomeiwen.com/subject/kohnhftx.html