【Android基礎】-View.MeasureSpec

簡介

MeasureSpec封裝了父元素對子元素的佈局要求。MeasureSpec對象代表了對寬或者高的佈局要求,它由大小(size)和模式(mode)組成,有如下三種模式:

  1. UNSPECIFIED:父元素對子元素尺寸沒有限制,子元素能獲得想要的任何大小;
  2. EXACTLY:父元素決定子元素的尺寸,不管子元素的實際尺寸;
  3. AT_MOST:父元素決定子元素的尺寸上限。

方法

  • public static int getMode (int measureSpec):獲取指定MeasureSpec的模式;
  • public static int getSize (int measureSpec):獲取指定MeasureSpec的尺寸;
  • public static int makeMeasureSpec (int size, int mode):根據尺寸和模式創建MeasureSpec實例;

使用

MeasureSpec通常在ViewGroup中用到,可以根據MeasureSpec裏面的參數調節子元素的大小。下面看看它在ListView.measureItem(View child)中的使用:

private void measureItem(View child) {
        ViewGroup.LayoutParams p = child.getLayoutParams();
        if (p == null) {
            p = new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
        }

        int childWidthSpec = ViewGroup.getChildMeasureSpec(mWidthMeasureSpec,
                mListPadding.left + mListPadding.right, p.width);
        int lpHeight = p.height;
        int childHeightSpec;
        if (lpHeight > 0) {
            childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
        } else {
            childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
        }
        child.measure(childWidthSpec, childHeightSpec);
    }
發佈了56 篇原創文章 · 獲贊 2 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章