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 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年05月05日 10时48分20秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
shell dirname basename
2021-07-04
线程分析
2021-07-04
jenkins
2021-07-04
DOM(总结)
2021-07-04
MySQL学习总结(一)
2021-07-04
MySQL学习总结(二)
2021-07-04
MySQL学习总结(三)
2021-07-04
未来已至,5G加持下的云游戏将走向何方?
2021-07-04
Mysql常用删除方式比较
2021-07-04
备案问题汇总
2021-07-04
“头号玩家”距离我们究竟有多远?
2021-07-04
首批!金山云获得可信金融云解决方案认证
2021-07-04
金山云张斯聪:探索沉浸式解决方案 提升教育云上体验
2021-07-04
高防弹性IP 金山云荣获“可信云技术最佳实践--网络安全”奖
2021-07-04
一周拿下百度Offer!211本+985硕+计算机专业~
2021-07-04
闭关三月!猛男逆道而行,四杀斩获阿里 / 腾讯 / 京东 / 百度等大厂 offer
2021-07-04
上线三天获 22w 浏览量!2021 最新一线大厂 Java 高级架构师面试题总结~
2021-07-04
电信物联网平台SOTA升级(软件升级)的全流程说明
2021-07-04
电信物联网平台插件开发相关总结
2021-07-04