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

更多相关文章

  1. Android(安卓)开发 框架系列 OkHttp使用详解
  2. Android(安卓)SDK和NDK区别
  3. Android开发(1)——项目结构
  4. Windows下快速搭建安卓开发环境android-studio
  5. Android开发中调用Spring CXF整合发布的WebService接口为什么抛
  6. Android(安卓)开发笔记 第三季 FragmentPagerAdapter
  7. Mac 下Idea开发android项目,模拟发短信
  8. 工程android配置windows7下cocos2d-x、android的开发环境
  9. 111111111

随机推荐

  1. 快速进入Android世界
  2. Android控件编辑时键盘弹起与关闭处理
  3. android的常用开发包
  4. Android(安卓)UI主线程与子线程
  5. 自定义实现圆形播放进度条(android,飞一般
  6. Android屏幕密度(Density)和分辨率的关系
  7. Android(安卓)ListView更换点击效果
  8. Android下基于XML的Graphics
  9. 在android中ScrollView嵌套ScrollView解
  10. Android屏幕适配攻略