ViewGroup记录_(1)

有的时候经常看到这样class  ****  extends ViewGroup{            } 经过在网上的查阅资料 以及自己的学习记录下对ViewGroup的学习。

通常我们需要实现三个步骤: onMeasure  onLayout  draw

1.onMeasure 计算控件大小  计算VIewGroup的空间大小

onMeasure传入的widthMeasureSpec和heightMeasureSpec不是一般的尺寸数值,而是将模式和尺寸组合在一起的数值。我们需要通过

int mode = MeasureSpec.getMode(widthMeasureSpec)得到模式,用int size = MeasureSpec.getSize(widthMeasureSpec)得到尺寸。

mode共有三种情况,取值分别为MeasureSpec.UNSPECIFIED, MeasureSpec.EXACTLY, MeasureSpec.AT_MOST。


MeasureSpec.EXACTLY是精确尺寸,当我们将控件的layout_width或layout_height指定为具体数值时如andorid:layout_width="50dip",或者为FILL_PARENT是,都是控件大小已经确定的情况,都是精确尺寸。


MeasureSpec.AT_MOST是最大尺寸,当控件的layout_width或layout_height指定为WRAP_CONTENT时,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可。因此,此时的mode是AT_MOST,size给出了父控件允许的最大尺寸。


MeasureSpec.UNSPECIFIED是未指定尺寸,这种情况不多,一般都是父控件是AdapterView,通过measure方法传入的模式。


protected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {

super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// 获取的是ViewGroup的mode和size
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
System.out.println("Width:" + widthMode + "/" + widthSize);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
System.out.println("Height:" + heightMode + "/" + heightSize);

int count = getChildCount();
for (int i = 0; i < count; i ++) {
View view = getChildAt(i);
// int childWidthSpec = MeasureSpec.makeMeasureSpec(100, MeasureSpec.EXACTLY);
// int childHeightSpec = MeasureSpec.makeMeasureSpec(48, MeasureSpec.EXACTLY);
// view.measure(childWidthSpec, childHeightSpec);
this.measureChild(view, widthMeasureSpec, heightMeasureSpec);
}
setMeasuredDimension(widthSize, heightSize);

}

2.onLayout 把每个控件布局到ViewGroup中

protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int count = getChildCount();
int widthSpan = 0;
int heightSpan = 0;
for (int i = 0; i < count; i ++) {
View child = getChildAt(i);
child.layout(widthSpan, heightSpan, widthSpan + child.getMeasuredWidth(), heightSpan + child.getMeasuredHeight());
widthSpan += child.getMeasuredWidth() + 10;
// heightSpan += child.getMeasuredHeight();
}
}

3. draw  

从网上找到的资料解释说Android已经为我们封装好了绘图过程,事故这些方法可不用写。

@Override
public void draw(Canvas canvas) {
super.draw(canvas);
}

@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}

@Override
protected void dispatchDraw(Canvas canvas) {
super.dispatchDraw(canvas);
}

完成之后就是ViewGroup的简单记录  待改天认真深入研究 献上demo运行效果图。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值