android中MeasureSpec的使用
2016-03-14 17:16
561 查看
最近看了一本书android群英传其中看了下View的测量在这里做个记录吧。
对View的测量模式中共可以分为三种:
EXACTLY
即精确模式,当我们将控件的layout_width或layout_height属性指定为具体值时,比如android:layout_width=”100dp”或android:layout_height=”match_parent”系统使用的是EXACTLY模式。
AT_MOST
即最大值模式,当控件的layout_Width或layout_height属性指定为wrap_content时,控件大小一般随着控件的子控件或内容的变化而变化,此时控件的尺寸只要不超过父控件允许的最大控件即可。
UNSPECIFIED
不指定其大小测量模式,View想多大就多大,通常情况下在绘制自定义View的时候使用。
View类默认的测量支持的是EXACTIY模式。
下面是一个小demo就是想给一个View默认的宽高为200,这就要求我们自定义View重写onMeasure方法。
就是这么简单就能很好使用MeasureSpec的测量模式了。
如果我们不重写onMeasure()方法那View就会填充整个父布局:
如果我们重复写了onMeasure方法实现的效果就如下:
对View的测量模式中共可以分为三种:
EXACTLY
即精确模式,当我们将控件的layout_width或layout_height属性指定为具体值时,比如android:layout_width=”100dp”或android:layout_height=”match_parent”系统使用的是EXACTLY模式。
AT_MOST
即最大值模式,当控件的layout_Width或layout_height属性指定为wrap_content时,控件大小一般随着控件的子控件或内容的变化而变化,此时控件的尺寸只要不超过父控件允许的最大控件即可。
UNSPECIFIED
不指定其大小测量模式,View想多大就多大,通常情况下在绘制自定义View的时候使用。
View类默认的测量支持的是EXACTIY模式。
下面是一个小demo就是想给一个View默认的宽高为200,这就要求我们自定义View重写onMeasure方法。
@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec)); } /**计算控件宽度*/ private int measureWidth(int widthMeasureSpec) { int result = 0; int specMode = MeasureSpec.getMode(widthMeasureSpec); int specSize = MeasureSpec.getSize(widthMeasureSpec); //精确值模式 if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = 200; //默认的宽度 if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; } /**计算控件高度*/ private int measureHeight(int heightMeasureSpec) { int result = 0; int specMode = MeasureSpec.getMode(heightMeasureSpec); int specSize = MeasureSpec.getSize(heightMeasureSpec); if (specMode == MeasureSpec.EXACTLY) { result = specSize; } else { result = 200; //默认的高度 if (specMode == MeasureSpec.AT_MOST) { result = Math.min(result, specSize); } } return result; }
就是这么简单就能很好使用MeasureSpec的测量模式了。
如果我们不重写onMeasure()方法那View就会填充整个父布局:
如果我们重复写了onMeasure方法实现的效果就如下:
相关文章推荐
- Android AutoLayout全新的适配方式 堪称适配终结者
- Android设计模式系列(9)--SDK源码之适配器模式
- Android 编程下获得应用程序的签名
- Android设计模式系列(8)--SDK源码之工厂方法模式
- android 拍照 图片剪切
- Android二维码的扫描和生成(ZXing)
- Android PRODUCT_COPY_FILE宏 使用方法
- 想要阻断短信通知必须成为android4.4默认短信应用,并且阻断两种广播才能做到
- Android控件的坑
- Android进程间通信(IPC)机制Binder简要介绍和学习plan
- ArcGIS4Android 3 :最快Android模拟器Genymotion
- Android基础-Notification用法
- Android中糟糕的AsyncTask
- android LayoutInflater使用
- 一步一步开发安卓应用 Android 启动界面的制作
- android短信拦截示例代码
- GitHub Top 100的Android开源库
- Android Activity和Fragment的转场动画
- Android设计模式系列(7)--SDK源码之命令模式
- Android仿IOS地区弹出框选择器