【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);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值