onMeasure的完美表述

本文详细介绍了自定义View中onMeasure方法的实现细节,包括如何根据MeasureSpec计算View的宽高,并考虑不同模式下(EXACTLY、AT_MOST、UNSPECIFIED)的处理方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

onMeasure

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @Override  
  2.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  
  3.     {  
  4.         int width = measureWidth(widthMeasureSpec);  
  5.         int height = measureHeight(heightMeasureSpec);  
  6.         setMeasuredDimension(width, height);  
  7.   
  8.         mRealWidth = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();  
  9.         mTextStartX = mRealWidth / 2 - mTextWidth / 2;  
  10.   
  11.     }  
  12.   
  13.     private int measureHeight(int measureSpec)  
  14.     {  
  15.         int mode = MeasureSpec.getMode(measureSpec);  
  16.         int val = MeasureSpec.getSize(measureSpec);  
  17.         int result = 0;  
  18.         switch (mode)  
  19.         {  
  20.         case MeasureSpec.EXACTLY:  
  21.             result = val;  
  22.             break;  
  23.         case MeasureSpec.AT_MOST:  
  24.         case MeasureSpec.UNSPECIFIED:  
  25.             result = mTextBound.height();  
  26.             break;  
  27.         }  
  28.         result = mode == MeasureSpec.AT_MOST ? Math.min(result, val) : result;  
  29.         return result + getPaddingTop() + getPaddingBottom();  
  30.     }  
  31.   
  32.     private int measureWidth(int measureSpec)  
  33.     {  
  34.         int mode = MeasureSpec.getMode(measureSpec);  
  35.         int val = MeasureSpec.getSize(measureSpec);  
  36.         int result = 0;  
  37.         switch (mode)  
  38.         {  
  39.         case MeasureSpec.EXACTLY:  
  40.             result = val;  
  41.             break;  
  42.         case MeasureSpec.AT_MOST:  
  43.         case MeasureSpec.UNSPECIFIED:  
  44.             // result = mTextBound.width();  
  45.             result = mTextWidth;  
  46.             break;  
  47.         }  
  48.         result = mode == MeasureSpec.AT_MOST ? Math.min(result, val) : result;  
  49.         return result + getPaddingLeft() + getPaddingRight();  
  50.     }  

关于测量,也是比较传统的写法,根据传入的widthMeasureSpec、heightMeasureSpec,利用MeasureSpec分别获取模式和值,如何是EXACTLY万事大吉,如果是AT_MOST、UNSPECIFIED那么就进行自己测量需要的空间,当然了,最好注意如果是AT_MOST不应该大于父类传入的值。

这里提一下,如果偷懒的话,可以选择继承TextView,然后测量就不需要写了,TextView默认帮你实现了,还能利用TextView的一些属性,不过咱们这个例子比较简单,我最终还是选择了继承View,继承View有种everything under control 的感觉。

测量完成以后,不用说都是绘制了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值