在Android中如何测量View的宽度和高度
16lz
2021-01-26
Android如何测量View的宽度和高度
手动去测量view的宽度和高度在开发时候会经常使用,在此介绍个比较简单的也是很常用的,其他方式暂不讨论,以textview为例
int widthSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); int heightSpec = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED); textView.measure(widthSpec, heightSpec); int measuredHeight = textView.getMeasuredHeight();//测量得到的textview的高 int measuredWidth = textView.getMeasuredWidth();//测量得到的textview的宽
我们点击View.MeasureSpec.UNSPECIFIED源码会看到值0,在View.MeasureSpec.UNSPECIFIED测量模式下,makeMeasureSpec()后widthSpec和heightSpec都是0
在测量的时候只需要textView.measure(0, 0)
就测量可以了
可以简化的写法
textView.measure(0,0); int measuredHeight = textView.getMeasuredHeight();//测量得到的textview的高 int measuredWidth = textView.getMeasuredWidth();//测量得到的textview的宽
也欢迎大家扫描二维码注我的微信订阅号,Android,java,kotlin,架构等技术讨论,共同进阶为Android高级开发,甚至资深Android开发
秦小怪.jpg
更多相关文章
- Android(安卓)开发 框架系列 OkHttp使用详解
- Android(安卓)SDK和NDK区别
- Android开发(1)——项目结构
- Windows下快速搭建安卓开发环境android-studio
- Android开发中调用Spring CXF整合发布的WebService接口为什么抛
- Android(安卓)开发笔记 第三季 FragmentPagerAdapter
- Mac 下Idea开发android项目,模拟发短信
- 工程android配置windows7下cocos2d-x、android的开发环境
- 111111111