手机
当前位置:查字典教程网 >编程开发 >安卓软件开发 >解析:继承ViewGroup后的子类如何重写onMeasure方法
解析:继承ViewGroup后的子类如何重写onMeasure方法
摘要:1.首先贴上我试验成功的代码复制代码代码如下:protectedvoidonMeasure(intwidthMeasureSpec,inth...

1.首先贴上我试验成功的代码

复制代码 代码如下:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

int measureWidth = MeasureSpec.getSize(widthMeasureSpec);

int measureHeigth = MeasureSpec.getSize(heightMeasureSpec);

setMeasuredDimension(measureWidth, measureHeigth);

// TODO Auto-generated method stub

for(int i= 0;i<getChildCount();i++){

View v = getChildAt(i);

Log.v(TAG, "measureWidth is " +v.getMeasuredWidth() + "measureHeight is "+v.getMeasuredHeight());

int widthSpec = 0;

int heightSpec = 0;

LayoutParams params = v.getLayoutParams();

if(params.width > 0){

widthSpec = MeasureSpec.makeMeasureSpec(params.width, MeasureSpec.EXACTLY);

}else if (params.width == -1) {

widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.EXACTLY);

} else if (params.width == -2) {

widthSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.AT_MOST);

}

if(params.height > 0){

heightSpec = MeasureSpec.makeMeasureSpec(params.height, MeasureSpec.EXACTLY);

}else if (params.height == -1) {

heightSpec = MeasureSpec.makeMeasureSpec(measureHeigth, MeasureSpec.EXACTLY);

} else if (params.height == -2) {

heightSpec = MeasureSpec.makeMeasureSpec(measureWidth, MeasureSpec.AT_MOST);

}

v.measure(widthSpec, heightSpec);

}

}

解释一下:

首先判断params.width的值是多少,有三种情况。

如果是大于零的话,及传递的就是一个具体的值,那么,构造MeasupreSpec的时候可以直接用EXACTLY。

如果为-1的话,就是MatchParent的情况,那么,获得父View的宽度,再用EXACTLY来构造MeasureSpec。

如果为-2的话,就是wrapContent的情况,那么,构造MeasureSpec的话直接用一个负数就可以了。

【解析:继承ViewGroup后的子类如何重写onMeasure方法】相关文章:

解析Android应用启动后自动创建桌面快捷方式的实现方法

Android的Service应用程序组件基本编写方法

android全屏去掉title栏的多种实现方法

Android Intent启动别的应用实现方法

Android ListView数据绑定显示的三种解决方法

通过OpenGL ES混合模式缩放视频缓冲区来适应显示尺寸

解析在Android中为TextView增加自定义HTML标签的实现方法

android layout XML解析错误的解决方法

解析离线安装Eclipse的Android ADT开发插件的具体操作(图文)

解析Android开发中多点触摸的实现方法

精品推荐
分类导航