很久都没有写博客了,今天有时间写点东西。上篇blog主要是用到了自定义控件的绘制方法,接下来说一下,自定义控件的车辆和布局方法。首先我们来自己实现一个Linearlayout控件。
如下图所示:
上图,是自定义的一个ViewGroup,模拟线性布局的效果,里面装载了三个Textview,很直观吧。好的,我们知道,要实现布局控件,一般我们会继承自ViewGroup。然后重写三个方法就可以了,onSizeChanged(),根据字面意思,当尺寸改变的时候,调用的方法,当然,我们界面第一次启动,或者从新打开的时候,都会调用这个方法。
onMeasure(),测量。主要是对控件测量高度,宽度。用的。
onLayout().布局,我们平时用的线性、相对、帧布局。都是在这个方法里面来操作子View的排布。从而达到其效果。
接下来,我们开始,创建工程,写一个类继承viewgroup,定义变量。
//父控件的宽度
int layoutWidth;
//父控件的高度
int layoutHeight;
需要重写如下几个方法:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 不能删除,用于父控件测量用
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}
在onSizeChanged()中我们先得到父控件的大小如下:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
layoutHeight = h;
layoutWidth = w;
Log.w("renk", "onSizeChanged");
}
然后我们开始最重要的测量工作,
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// 不能删除,用于父控件测量用
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
Log.w("renk", "onMeasure");
int childViewCount = this.getChildCount();
for (int i = 0; i < childViewCount; i++) {
View childView = this.getChildAt(i);
int width = MeasureSpec.getSize(widthMeasureSpec);
widthMeasureSpec = MeasureSpec.makeMeasureSpec(width,
MeasureSpec.AT_MOST);
int height =MeasureSpec.getSize(heightMeasureSpec);
heightMeasureSpec =MeasureSpec.makeMeasureSpec(height,
MeasureSpec.AT_MOST);
//测量后让子View获得宽高
childView.measure(widthMeasureSpec, heightMeasureSpec);
}
}
这里需要说一下,MeasureSpec.AT_MOST是一种显示模式(mode)。mode共有三种情况,分别为MeasureSpec.UNSPECIFIED,MeasureSpec.EXACTLY,MeasureSpec.AT_MOST。
MeasureSpec.EXACTLY是精确尺寸,当我们将控件的layout_width或layout_height指定为具体数 时如andorid:layout_width=”90dp”,或者为Match_PARENT是,都是控件大小已经确定的情况,都是精确尺寸。
MeasureSpec.AT_MOST是最大尺寸,当控件的layout_width或者layout_height指定为WRAP_CONTENT时,控件大小一般随着控件的子空间或内容进行变化,此时控件尺寸只要不超过父控件允许的最大尺寸即可。因此,此时的mode是AT_MOST,size给出