Android MeasureSpec介绍及使用详解
发布日期:2021-06-30 22:35:04 浏览次数:3 分类:技术文章

本文共 2378 字,大约阅读时间需要 7 分钟。

说明:

一个MeasureSpec封装了父布局传递给子布局的布局要求,每个MeasureSpec代表了一组宽度和高度的要求。一个MeasureSpec由大小和模式组成。它有三种模式:UNSPECIFIED(未指定),父元素不对子元素施加任何束缚,子元素可以得到任意想要的大小;EXACTLY(完全),父元素决定子元素的确切大小,子元素将被限定在给定的边界里而忽略它本身大小;AT_MOST(至多),子元素至多达到指定大小的值。

它常用的三个函数:

  1.static int getMode(int measureSpec):根据提供的测量值(格式)提取模式(上述三个模式之一)

  2.static int getSize(int measureSpec):根据提供的测量值(格式)提取大小值(这个大小也就是我们通常所说的大小)

  3.static int makeMeasureSpec(int size,int mode):根据提供的大小值和模式创建一个测量值(格式)

/**     * 测量     */    @Override    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        // 第一步:先测量文本的区域大小        measureText();        // 第二步:对视图测量        int width = measureWidth(widthMeasureSpec);        int height = measureHeight(heightMeasureSpec);        // 这个方法决定了当前View的大小        setMeasuredDimension(width, height);                }    /**     * 测量高度     * @param heightMeasureSpec     * @return     */    private int measureHeight(int heightMeasureSpec) {        int height = 0;        int heightSize = MeasureSpec.getSize(heightMeasureSpec);        int heightMode = MeasureSpec.getMode(heightMeasureSpec);        switch (heightMode) {        case MeasureSpec.EXACTLY:            height = heightSize;            break;        case MeasureSpec.AT_MOST:        case MeasureSpec.UNSPECIFIED:            height = mBound.height() + getPaddingBottom() + getPaddingTop();            break;        }        return height;    }    /**     * 测量宽度     * @param widthMeasureSpec     * @return     */    private int measureWidth(int widthMeasureSpec) {        int width = 0;        int widthtSize = MeasureSpec.getSize(widthMeasureSpec);        int widthMode = MeasureSpec.getMode(widthMeasureSpec);        switch (widthMode) {        case MeasureSpec.EXACTLY:            width = widthtSize;            break;        case MeasureSpec.AT_MOST:        case MeasureSpec.UNSPECIFIED:            width = mBound.width() + getPaddingLeft() + getPaddingRight();            break;        }        return width;    }    /**     * 对文本控件测量,得到绘制时的宽高     */    private void measureText() {        mTextWidth = (int) mPaint.measureText(mText);        // FontMetrics fm = mPaint.getFontMetrics();        // 文本的最低处-文本的最高处        // mTextHeight = (int) Math.ceil(fm.descent - fm.top);        mBound = new Rect();        mPaint.getTextBounds(mText, 0, mText.length(), mBound);        // 获得高度        mTextHeight = mBound.height();    }

转载地址:https://lovoo.blog.csdn.net/article/details/51226975 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Android 简单模仿AsyncHttpClient
下一篇:Android 继承ViewGroup必须重写onMeasure方法和onLayout方法

发表评论

最新留言

很好
[***.229.124.182]2024年05月05日 10时48分20秒